reference and destructor in c++

c++, destructor, reference

Solution

When you have:

B b = a->getB();

a new object of type `B` is created from a reference to existing instance of `B` (`B&`). It is not the `B::operator=` that is called here but copy constructor.

Each class has a copy constructor (if you don't add it explicitly, compiler will provide one for you). It accepts a single argument which is a reference to the same class. You haven't put copy constructor in the code above so I assume that compiler has generated one for you:

class B
{
public:
   B(B& other)
   {
      // memberwise copy (shallow copy) 
   };
};

So `A::getB()` returned a reference to member `A::b` and this reference was passed as an argument to `B::B(B&)`.

void func()
{
   A *a = new A();  // Instance of A is created on the heap;
                    // (pointer a is a local variable and is on the stack though!)
                    // A::b is object of type B and it is on the heap as well  

   B b = a->getB(); // Instance of class B is created on the stack (local variable)
   .....
   delete a;        // deleting A from the heap: 
                    // A::~A is called which calls B::~B (of its member b)
} // a and b go out of the scope; b is an object => B::~B is called                    

Problem

I have the following class: ``` class A { public: B& getB() {return b;} private: B b; }; class B { ~B() {cout<<"destructor B is called";} ... }; void func() { A *a = new a; B b = a->getB(); ..... } ``` Why does the destructor of class B is called when exiting the function func? Doest the function getB return a referance to the object B? if class A still exists at the end of function func, why does the destructor of B is called?

Original source