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?
When you have:
a new object of type
Bis created from a reference to existing instance ofB(B&). It is not theB::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:
So
A::getB()returned a reference to memberA::band this reference was passed as an argument toB::B(B&).