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?
B b = a->getB();
will be calling the copy constructor B(const& B)
so you are creating a new object on the stack with is a copy of the object returned by the reference.
Use instead:
B& b = a->getB();
and no destructor will be called since you won't create a new B object
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With