I am getting a seg fault when trying to add a pointer to an object to a vector in an instance of another object. I am adding multiple pointers to the vector at once and the first one works but the second attempt keeps tossing seg faults.
class Observer {
Observer();
observe();
};
class Subject {
std::vector<Observer*> *observers;
std::string name;
Subject();
virtual std::string getName();
virtual void addObserver(Observer *observer) {
observers->push_back(observer);
}
};
class Base : public Subject {
Base(std::string newName) { name = newName; }
};
class Derivative : public Subject, public Observer {
float a;
float b;
float c;
Derivative(a, b, c) { this->a = a; this->b = b; this->c = c; }
};
class Board : public Base {
Base *base;
Board(std::string newName, Base *newBase) { name = newName; base = newBase; }
void initializeDerivatives(int start, int end) {
for (int i = start; i <= end; ++i) {
addObserver(new Derivative(start, start + 1, start + 2)); //works
base->addObserver(new Derivative(start, start + 1, start + 2)); //THIS WORKS
addObserver(new Derivative(start, start + 2, start + 3)); //works
base->addObserver(new Derivative(start, start + 2, start + 3)); //seg fault here
}
}
};
int main() {
Base myBase("MYBASE");
Board myBoard("MYBASE", myBase);
myBoard.initializeDerivatives(1, 10);
}
I was getting seg faults earlier when I declared myBoard and myBase as pointers: Base* myBase = new Base("MYBASE"); Board* myBoard = new Board("MYBASE", myBase);
And I was unsure why that was since I thought using the new operator would actually initialize the instance of the object. Changing it to make the actual objects still allows me to add one pointer to the observers vector, but the second one isn't working. Any thoughts?