Search code examples
c++inheritancepolymorphismabstraction

C++ Inheritance of abstract reference members for polymorphism


I have an abstract class with N protected members:

class Something {
protected:
    UINT someVal;
    std::vector<SomeType> g_MyVec;
    // some virtual abstract methods ...
public:
    UINT getSomeVal() { return someVal; }
    std::vector<SomeType> GetVec() { return g_MyVec; }
}

class SubClass : public Something {
public:
    SubClass() { // no members in this class, all inherited from super
        someVal = 5; // this sticks
        g_myVec = { .. correct initialization }; // this doesn't stick
    }
}

The client of this code does:

Something* s = &SubClass();
s->getSomeVal(); // OK, has 5 in it.
s->GetVec(); // Nada, it returns 0 size, nothing at all... WHY?!

Enlightenment is much appreciated.


Solution

  • You are taking an address of the temporary. It's a UB and incorrect code. Subclass gets destroyed along with the vector after the ;

    Correct way to do this would be (Assuming no C++11):

    Something* s = new Subclass();
    s->getSomeVal(); // OK, has 5 in it.
    s->GetVec(); 
    delete s;