We are unable to copy derived class objects, when copy constructor of base class is private ,but when we write our own copy constructor in derived class , then we are able to copy object , Why?
#include <iostream>
class base
{
public:
base()
{
}
private:
base(const base &x)
{
std::cout << "copy constructor of base class";
}
};
class derived : public base
{
public:
derived(){};
derived(const derived &X) //If we remove this, we are not able to create copy? But why?
{
std::cout << "copy of derived class";
}
};
int main()
{
derived x;
derived y(x);//valid with our own derived class copy constructor
}
Just to understand this after reading comments and answer , I wrote another program
#include <iostream>
class base
{
protected:
int x;
int y;
public:
base() {}
base(int x, int y) : x(x), y(y)
{
}
};
class derived : public base
{
int a;
public:
derived()
{
}
derived(int a, int x, int y) : a(a), base(x, y){};
derived(derived const &x)
{
this->a = x.a;
}
void get()
{
std::cout << a;
std::cout << "\t" << x << "\t" << y;
}
};
int main()
{
derived a(99, 2, 3);
a.get();
derived b(a);
std::cout << std::endl;
b.get();
}
This gave me output as
99 2 3
99 -2145089504 1
Also I found Why aren't copy constructors "chained" like default constructors and destructors? worth a read