I'm getting my head around inheritance in c++, and trying to implement a basic setup in which a base class has a) an abstract method fire() which subclasses must implement and b) a variable which subclasses inherit.
My set up works as expected, but only when I create the object immediately before using it (see "option 1" below). When I create the object elsewhere (see "option 2") the (*p).getSomeDouble() call seems to cause problems.
So my questions are, is this the right overall approach? And if so, how do I get "option 2" to work?
EDIT: thanks for the comments on scope, good point, but that doesn't really answer my questions on whether my overall approach is correct and how I can correctly create the object elsewhere then pass it (i.e. how to get this to actually work).
class BaseClass{
public:
virtual void fire() = 0;
// Use a getter and setter as you can't make a variable virtual in c++
virtual double getSomeDouble(){ return someDouble; }
virtual void setSomeDouble(double d){ someDouble = d; }
private:
double someDouble;
};
class DerivedClass : public BaseClass{
public:
void fire();
};
class AnotherClass{
public:
// Set up a DerivedClass object and set someDouble to 1
BaseClass * getDerivedObject(){
DerivedClass object;
object.setSomeDouble(1);
BaseClass * p = &object;
return p;
};
};
void DerivedClass::fire(){ cout << "Derived class fired. Yay." << endl; }
int main()
{
// Option 1 - set up object here. Everything works fine.
/*DerivedClass object;
object.setSomeDouble(1);
BaseClass * p = &object;*/
// Option 2 - set up object in AnotherClass
AnotherClass a;
BaseClass * p = a.getDerivedObject(); // at this point, p looks fine in my IDE (someDouble = 1)
cout << to_string( (*p).getSomeDouble() ); // with option 2, this prints a nonsense value (and the data my IDE returns for *p has changed)
(*p).fire(); // with option 2, this fails with " Access violation reading location 0xCCCCCCCC."
return 0;
}