Copy Inheritance Constructor

struct A{
  virtual void what() { cout << "Base" << endl; };
};

struct B : A {
  virtual void what() { cout << "Sub" << endl; };
  int m;
  B() : m(10) {};
  B(const A & x) : m(50) {};
};

void main() {
  B b1;
  B b2 = b1;
  cout << "Number:  "
       << b2.m << endl;
};

Why not b2.m = 50? I am trying to copy a b-object, and I have copy constructor B (const A and x): m (50). Do I need to make a copy of c'tor for a derived class? Like B (const B & x) ?? I thought that since the b-object has a part, we could use B (const A and x): m (50) instead of the default constructor :: S

In the case when you have a function with the parameter of object A, you can send object B. Why is it different from the copy constructor?

+5
source share
3 answers

, B(const A& x) copy-ctor - T lvalue T ( , ). copy-ctor, , , b2.m b1.m.

X , X&, const X&, volatile X& const volatile X&, , (8.3.6).

+14

.

. B(const A & x) - , const A .

, "", "". , B(const B &x).

+1

By default, copy-ctor for classes of type B will be B (const B &). Since you did not specify this, the compiler kindly generates it for you.

It differs from user methods because they cannot be generated by the compiler.

+1
source

All Articles