Search code examples
c++classvector2d-vector

2D Vector of Class gets error when accessing function


After converting my 2D array to a 2D vector (due to all the praise I heard about it), my program breaks almost immediately, and after some testing, it appears to happen when the program tries to do a function with a vector element. I have made some simplified source code, which also has the error:

#include <iostream>
#include <vector>

using namespace std;

class Dog
{
    private:
        int mass, size;
    public:
        void setMass(int);
        void setSize(int);

        int getMass();
        int getSize();
};

void Dog::setMass(int newMass) {mass = newMass;}
void Dog::setSize(int newSize) {size = newSize;}

int Dog::getMass() {return mass;}
int Dog::getSize() {return size;}

int main() 
{
    vector <vector<Dog*> > dogs(10, vector<Dog*> (10));

    dogs[0][0]->setMass(10);
    dogs[0][0]->setSize(5);
    return 0;
}

I also have a link to Ideone, so it is easier to test (and where I tested the code) http://ideone.com/e.js/mqVuv3


Solution

  • You have a 2D vector of pointer-to-Dog but are not allocating any Dog objects. When you initialize the 2D vector the pointers are initialized to nullptr. Dereferencing a nullptr is undefined behaviour.

    Unless you have a good reason not to, I suggest you just have a 2D vector of Dogs:

    vector<vector<Dog>> dogs(10, vector<Dog>(10));
    

    Then you will have 100 default constructed Dogs and you can happily set their mass and size:

    dogs[0][0].setMass(10);
    dogs[0][0].setSize(5);