ZAX9732
ZAX9732

Reputation: 85

Destructors not called?

I am trying to trace this program however for some reason it displays Process finished with exit code 4. and end without calling the destructors? what could be the cause?

#include <iostream>
using namespace std;

class A {
public:
    A() { cout << "A ctor" << endl; }
    A(const A& a) { cout << "A copy ctor" << endl; }
    virtual ~A() { cout << "A dtor" << endl; }
    virtual void foo() { cout << "A foo()" << endl; }
    virtual A& operator=(const A& rhs) { cout << "A op=" << endl; }
};

class B : public A {
public:
    B() { cout << "B ctor" << endl; }
    virtual ~B() { cout << "B dtor" << endl; }
    virtual void foo() { cout << "B foo()" << endl; }
protected:
    A mInstanceOfA; // don't forget about me!
};
A foo(A& input)
{
    input.foo();
    return input;
}
int main()
{
    B myB;

    B myOtherB;
    A myA;
    myOtherB = myB;
    myA = foo(myOtherB);
}

Upvotes: 0

Views: 69

Answers (2)

Felix Kimmerle
Felix Kimmerle

Reputation: 46

For me (with gcc 8.3.0) it works well. But I get a warning:

test.cpp: In member function ‘virtual A& A::operator=(const A&)’:
test.cpp:10:63: warning: no return statement in function returning non-void [-Wreturn-type]
 virtual A& operator=(const A& rhs) { cout << "A op=" << endl; }

And it prints out:

A ctor
A ctor
B ctor
A ctor
A ctor
B ctor
A ctor
A op=
A op=
B foo()
A copy ctor
A op=
A dtor
A dtor
B dtor
A dtor
A dtor
B dtor
A dtor
A dtor

Maybe you should try to solve the warning.

Upvotes: 3

Igor Tandetnik
Igor Tandetnik

Reputation: 52471

Your program exhibits undefined behavior, by way of reaching the closing brace of a non-void function (here, operator=) without encountering return statement.

Upvotes: 4

Related Questions