I do not understand two things:
1-In code 1 when the object d2 is defined,default constructor of Base class and copy constructor of Derived class invoked.but in code 2(derived class does not have copy constructor) just copy constructor of Base class invoked!
Why copy constructor of Base class? Is constructor of Derived class called?
2-What is the difference between
D d2 = d1 ;
and
D d2;
d2 = d1;
in this example? What is the reason for this?
code 1
//code 1
#include <iostream>
using std::cout;
using std::endl;
///////////////////////////
class B
{
protected:
int x;
public:
B()
{
x = 4;
cout << "default constructor of Base class " << endl;
}
B(int a)
{
x = a;
cout << "parametric constructor of Base class" << endl;
}
B(const B &b)
{
x = b.x;
cout << "copy constructor of Base class " << endl;
}
};
////////////////////////////////////////////////////////////
class D : public B
{
private:
int y;
public:
D()
{
y = 5;
cout << "default constructor of Derived class" << endl;
}
D(int k)
{
y = k;
cout << "parametric constructor of Derived class" << endl;
}
D(D& copy)
{
cout << "copy constructor of Derived class" << endl;
}
};
////////////////////////////////////////////////////////////
int main()
{
D d1(3);
D d2 = d1;
return 0;
}
code 2
//code 2
#include <iostream>
using std::cout;
using std::endl;
///////////////////////////
class B
{
protected:
int x;
public:
B()
{
x = 4;
cout << "default constructor of Base class " << endl;
}
B(int a)
{
x = a;
cout << "parametric constructor of Base class" << endl;
}
B(const B &b)
{
x = b.x;
cout << "copy constructor of Base class " << endl;
}
};
////////////////////////////////////////////////////////////
class D : public B
{
private:
int y;
public:
D()
{
y = 5;
cout << "default constructor of Derived class" << endl;
}
D(int k)
{
y = k;
cout << "parametric constructor of Derived class" << endl;
}
/* D(D& copy)
{
cout << "copy constructor of Derived class" << endl;
}
*/
};
////////////////////////////////////////////////////////////
int main()
{
D d1(3);
D d2 = d1;
return 0;
}