0

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;
}
Giswok
  • 559
  • 5
  • 16
  • 2
    Nothing to do with inheritance. This is just returning a pointer to a local object. – Sebastian Redl May 12 '15 at 13:13
  • You are returning a pointer to a stack object in `getDerivedObject()`. You must not use this pointer as it is pointing to a deleted object. – mkaes May 12 '15 at 13:13
  • Turns out all that's needed to get this to work and permit polymorphism is use of `new` to create `object`. Solutions are useful. For any interested visitors I was able to get an elegant answer to my main queries here: http://stackoverflow.com/questions/30194899/c-polymorphism-and-passing-subclasses-around – Giswok May 12 '15 at 17:21

0 Answers0