samedi 28 novembre 2015

C++ inheritance

So i have a C++ question about inheritance.

class X{
public:
 X()
 {
   cerr << "X()|";
 }
 X(const X& c)
 {
   cerr << "X(const X&)|";
 }
 ~X()
 {
   cerr << "~X()|";
 }
 X& operator=(const X& c)
 { 
   cerr << "X::op=|"; return *this;
 }
};

class B{
public:
 B()
 {
   cerr << "B()|";
 }
 B(const B& c):x1_(c.x1_)
 {
   cerr << "B(const B&)|";
 }
 virtual ~B()
 {
   cerr << "~B()|";
 }
 B& operator=(const B& c)
 { 
   cerr << "B::op=|"; 
   x1_=c.x1_;
   return *this;
 }
private:
 X x1_;
};

class D:public B{
public:
 D()
 {
   cerr << "D()|";
 }
 virtual ~D()
 {
   cerr << "~D()|";
 }
 private:
 X x2_;
};

Question 1:

when i run

B *pb = new B() result: X()|B()|

D *pd = new D() result: X()|B()|X()|D()|

why is that? B is not the child class of X?

Question 2:

D d(*pd)

*pd = d result: B::op=|X::op=|X::op=|

*pb = *pd result: B::op=|X::op=|

why is *pd = d have two X::op=| and *pb = *pd only have one X::op=|? can some one explain it?

Aucun commentaire:

Enregistrer un commentaire