Search code examples
c++classvectorpushback

Push back subclass objects in base class type 2d vector in C++


I really searched all over the internet and couldn't find a way to fix it, so here's my problem :

I created a class called "Gridpoint" to represent each point of a 2d map and then a 2d vector of type Gridpoint* to store and print the entire map (n^2 Gridpoint objects)

Also, I have a base class called "Ship" (that contains ships generally) and 6 subclasses for various types of ships with extra functions about them (ex. "Pirate").

So, I wanted to create an empty 2d vector of type Ship* with 6 rows to store at each row the objects created by each subclass. (ex. 4th row -> all Pirate ships).

However, although all objects (from the Ship subclasses) are created successfully, nothing is ever stored at the vector and it remains empty.

What should I do to push_back successfully each object at the correct row, the moment it's created ??

Below is a simplified version of all the functions that "participate" in the creation and the push_back of the vectors and the objects (only for subclass Pirate). For more info or code, just ask me :

void createShip0(vector<vector<GridPoint*>, vector<vector<Ship*> >, int, int, double, double, int, int, int)

int main()
{
    int n = 10;

    vector<GridPoint*> gcol(n);
    vector<vector<GridPoint*> > GridMap(n, gcol);

    vector<vector<Ship*> > ShipArray(7);

    int i = rand() % n;
    int j = rand() % n;
    double MxEnd = rand() % 5 + 5;
    int Sped = rand() % 3 + 1;

    createShip0(GridMap, ShipArray, i, j, MxEnd, MxEnd, Sped, 0, n);
}


void createShip0(vector<vector<GridPoint*> > GridMap, vector<vector<Ship*> > ShipArray, int xIn, int yIn, double MaxEnd, double CurEnd, int Speed, int TreasQ, int n)
{
    Pirate::createShip(GridMap, ShipArray, xIn, yIn, MaxEnd, CurEnd, Speed, TreasQ);
}



void Pirate::createShip(vector<vector<GridPoint*> > GridMap, vector<vector<Ship*> > ShipArray, int xIn, int yIn, double MaxEnd, double CurEnd, int Speed, int TreasQ)
{
    Pirate* obj = new Pirate(xIn, yIn, MaxEnd, CurEnd, Speed, TreasQ);
    ShipArray.at(3).push_back(obj); 
}

Solution

  • Your createShip0 function takes all its arguments by value, meaning they are are local copies in the body of the function, unseen on the caller side. You are doing the equivalent of this:

    void foo(int n) { n += 42; }
    

    Then

    int i = 0;
    foo(i);
    stc::cout << i << std::endl; // Output: 0
    

    and expecting i to have been incremented by 42. If you want the function's arguments to be modified at the caller side, you'd need to pass them by reference instead:

    void foo(int& n) { n += 42; }
    //          ^