0

In the following code, will small c will leak ?

I believe that not, as it is not dynamically allocated, the struct will be deleted entirely

From my peers I got the following answers :

  1. It is undefined behavior
  2. It will leak
  3. It wont leak

Here is the code :

class A 
{
    public:
    void printA() { cout << "A" << endl;}
    virtual void printB() { cout << "B" << endl;}
    int a;
};

class C : public A
{
    public :
    void printA() { cout << "C" << endl;}
    void printB() { cout << "D" << endl;}
    int c;
};

int main() 
{
    A* bla = new C();
    bla->printA();
    bla->printB();
    delete bla;
    return 0;
}
OopsUser
  • 4,642
  • 7
  • 46
  • 71
  • 2
    "as it is not dynamically allocated", `bla` is dynamically allocated, and thats all that matters, because `c` is member of it – 463035818_is_not_an_ai Nov 24 '22 at 14:02
  • 8
    _"...If expression evaluates to a pointer to a base class subobject of the object that was allocated with new, the destructor of the base class must be virtual, otherwise the behavior is undefined...."_ [delete expression](https://en.cppreference.com/w/cpp/language/delete) – Richard Critten Nov 24 '22 at 14:02
  • 1
    [Posssible duplicate](https://stackoverflow.com/questions/25220229/in-c-inheritance-derived-class-destructor-not-called-when-pointer-object-to-b) – PaulMcKenzie Nov 24 '22 at 14:02
  • 1
    its not only objects allocated by `new` whose memory has to be managed. Its just easily overlooked and/or ignored, that most memory is managed automatically in C++ – 463035818_is_not_an_ai Nov 24 '22 at 14:03
  • 1
    There's no such thing as a "virtual class". The issue here is simply about a base class without a virtual destructor. – Pete Becker Nov 24 '22 at 15:25

0 Answers0