-1

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.

Fer
  • 460
  • 2
  • 4
  • 17
  • 4
    You are taking an address of the temporary??? Its a UB and incorrect code. `Subclass` gets destroyed along with the vector after the `;` – Arunmu Jul 06 '16 at 20:22
  • 1
    What is the type of `UINT`? Is it `unsigned int`? uint32_t? uint16_t? uint8_t? You should review the types in `stdint.h`. – Thomas Matthews Jul 06 '16 at 20:26
  • @ThomasMatthews Looks like [Windows API data type](https://msdn.microsoft.com/en-us/library/windows/desktop/aa383751(v=vs.85).aspx) (but just speculation) and your comment is definitely relevant. – James Adkison Jul 06 '16 at 20:27
  • @JamesAdkison: Could be anything. I've seen many RTOS vendors and SDKs that use similar notation, all dating back before `uint` family was standardized. – Thomas Matthews Jul 06 '16 at 20:29
  • There is no abstract classes and no polymorphism in this code. Even superclass destructor is not virtual and can lead to memory leaks. – ilotXXI Jul 06 '16 at 21:04
  • Btw, a better way to construct the base members is to use a (possibly `protected`) constructor which initialises the base members, rather than do this in the function body of the derived class's constructor. – Walter Jul 06 '16 at 23:26
  • It really gets to me people trolling and penalizing others for not knowing all and asking legitimate questions. I think it defeats stack overflow's purpose. There are many concepts here like temporaries, UBs and things maybe some other-languages programmers are not familiar with. Downvoting with no reason is just a waste of everyone's time. – Fer Jul 07 '16 at 00:06

1 Answers1

4

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;
Arunmu
  • 6,837
  • 1
  • 24
  • 46
  • `new` and `delete` operators are not necessary. The pointer just must be used in less scope than an object it points to. In original code the object's scope is one line, the pointer is used after it. – ilotXXI Jul 06 '16 at 21:08