Consider this piece of code:
#include <vector>
#include <iostream>
using namespace std;
class Base
{
char _type;
public:
Base(char type):
_type(type)
{}
~Base() {
cout << "Base destructor: " << _type << endl;
}
};
class uncopyable
{
protected:
uncopyable() {}
~uncopyable() {}
private:
uncopyable( const uncopyable& );
const uncopyable& operator=( const uncopyable& );
};
class Child : public Base, private uncopyable
{
int j;
public:
Child():
Base('c')
{}
~Child() {
cout << "Child destructor" << endl;
}
};
int main()
{
vector<Base> v;
Base b('b');
Child c;
v.push_back(b);
v.push_back(c);
return 0;
}
The output on my system is:
Base destructor: b
Child destructor
Base destructor: c
Base destructor: b
Base destructor: b
Base destructor: c
My questions are:
Why is the destructor of
Base
(with type b) called three times instead of two (do we have more than two copies of object b)?What happens when we copy an object of type
Child
, considering the copy-constructor of one of its parents is private. Is it undefined behavior?I was expecting to get a compile-time error whenever I try to copy an object of type
Child
. I thought the child's default copy-constructor would try to call the private copy-constructor of the Uncopyable class and cause compilation error. Why doesn't it give compile errors?
The reason the code is designed this way is because the Child
class is huge.
The desired behavior is throwing away the child data whenever a client tries to copy a Child
object (calling the destructor of Child
without calling the destructor of Base
).
This piece of code achieves that, but I guess it results in undefined behavior and has memory leak (never calls the destructor of Child
for the copied instance).