I have a questing around such staff.
There is a class A which has a object of type class B as it's member. Since I'd like B to be a base class of group of other classes I need to use pointer or reference to the object, not it's copy, to use virtual methods of B inside A properly. But when I write such code
class B
{public:
B(int _i = 1): i(_i) {};
~B()
{i = 0; // just to indicate existence of problem: here maybe something more dangerous, like delete [] operator, as well!
cout << "B destructed!\n";
};
virtual int GetI () const {return i;}; // for example
protected:
int i;
};
class A
{public:
A(const B& _b): b(_b) {}
void ShowI () {cout <<b.GetI()<<'\n';};
private:
const B& b;
};
and use it this way
B b(1);
A a(b);
a.ShowI();
it works perfectly:
1
B destructed!
But
A a(B(1));
a.ShowI();
give very unwanted result: object b creates and a.b is set as reference to it, but just after constructor of A finished, object b destructs! The output is:
B destructed!
0
I repeat again, that using copy of instead of reference to b in A
class A
{public:
A(B _b): b(_b) {}
void ShowI () {cout <<b.GetI()<<'\n';};
private:
B b;
};
won't work if B is base class and A calls it's virtual function. Maybe I'm too stupid since I do not know not know proper way to write necessary code to make it works perfectly (then I'm sorry!) or maybe it is not so easy at all :-(
Of course, if B(1) was sent to function or method, not class constructor, it worked perfect. And of course, I may use the same code as in this problem as described here to create B as properly cloneable base or derived object, but doesn't it appears too hard to for such easy looking problem? And what if I want to use class B that I could not edit?