I’m getting some nasty segmentation faults through the g++ compiler on the following code. Any ideas on why this would happen and how to fix it would be great.
#include <iostream>
using namespace std;
class Base {
public:
Base() {}
virtual ~Base() {};
virtual int getNum(int) = 0;
};
class Derived: public Base {
public:
Derived() :
Base() {}
~Derived() {}
int getNum(int num) {
return num;
}
};
class Foo {
public:
Foo() {
};
void init() {
Derived n;
*baseId = n;
}
void otherStuff() {
cout << "The num is" << baseId->getNum(14) << baseId->getNum(15) << baseId->getNum(16) << baseId->getNum(15) << endl;
}
Derived* baseId;
};
int main() {
Foo f;
f.init();
f.otherStuff();
return 0;
}
Apart from what Neil noted, derived
nis local to your init function. It “dies” when you exit the function, so even if you assigned it correctly, it won’t work.What you want is not assigning on the stack but on the heap:
or even better:
and a destructor and constructor pair to prevent problems :
If going for this method, be sure to either block copy constructor and assignment operator, or implement them properly. To implement them however, you’d need to implement copying of Derived too — or best: use a safe shared_ptr to store the pointer.