aboutsummaryrefslogtreecommitdiff
path: root/cpp04/ex02/Squad.cpp
blob: d1d988f781a2b3e8981bc43880d8831057c4dadd (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
/* ************************************************************************** */
/*                                                                            */
/*                                                        :::      ::::::::   */
/*   Squad.cpp                                          :+:      :+:    :+:   */
/*                                                    +:+ +:+         +:+     */
/*   By: charles <charles.cabergs@gmail.com>        +#+  +:+       +#+        */
/*                                                +#+#+#+#+#+   +#+           */
/*   Created: 2020/04/14 15:08:35 by charles           #+#    #+#             */
/*   Updated: 2020/11/12 15:38:55 by cacharle         ###   ########.fr       */
/*                                                                            */
/* ************************************************************************** */

#include "Squad.hpp"

Squad::Squad() : m_units(new ISpaceMarine*[0]), m_size(0) {}

Squad::Squad(Squad const& other) { *this = other; }

Squad& Squad::operator=(Squad const& other)
{
    destroyUnits();
    m_size = other.m_size;
    m_units = new ISpaceMarine*[m_size];
    for (int i = 0; i < m_size; i++)
        m_units[i] = other.m_units[i]->clone();
    return *this;
}

Squad::~Squad() { destroyUnits(); }

int Squad::getCount() const { return m_size; }

ISpaceMarine* Squad::getUnit(int n) const
{
    if (n < 0 || n >= m_size)
        return NULL;
    return m_units[n];
}

int Squad::push(ISpaceMarine* spaceMarine)
{
    if (spaceMarine == NULL)
        return (-1);
    for (int i = 0; i < m_size; i++)
        if (m_units[i] == spaceMarine)
            return (-1);

    ISpaceMarine** new_units = new ISpaceMarine*[m_size + 1];
    for (int i = 0; i < m_size; i++)
        new_units[i] = m_units[i];
    new_units[m_size] = spaceMarine;
    delete [] m_units;
    m_size++;
    m_units = new_units;
    return m_size;
}

void Squad::destroyUnits()
{
    for (int i = 0; i < m_size; i++)
        delete m_units[i];
    delete [] m_units;
}