-4

In class A, I do not define any constructor that takes parameters. In class B, which is a derived class of class A, I define a copy constructor and it passes a reference of B to the constructor of A. It is so weird to see this code does pass the compiling and the output is below. Could someone explain it a little bit?

// Example program
#include <iostream>
#include <string>

class A{
  public:
    A(){ std::cout<<"A constructor called"<<std::endl;};
    ~A(){};
};

class B:private A{
  public:
    B(){std::cout<<"B default constructor called"<<std::endl;};

    B(const B& b): A(b){std::cout<<"B constructor called"<<std::endl;};
};

int main()
{
  B b{};
  B b2{b};
  return 0;
}

output

 A constructor called
 B default constructor called
 B constructor called
Wubin Ouyang
  • 777
  • 1
  • 7
  • 9
  • Possible duplicate of [Conditions for automatic generation of default/copy/move ctor and copy/move assignment operator?](https://stackoverflow.com/questions/4943958/conditions-for-automatic-generation-of-default-copy-move-ctor-and-copy-move-assi) –  Feb 02 '18 at 17:05
  • 2
    I don't think this question is so bad. It's well-written, with example code, and the output is given. – Bathsheba Feb 02 '18 at 17:08

2 Answers2

3

A(b) calls the copy constructor in A, which has been provided by the compiler for you.

See for yourself by writing

A(const A& a) {std::cout << "A copy constructor called\n";}

in class A. This is all perfectly well defined C++.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
0

I figured it out five minutes after I asked. It is actually calling the copy constructor of A which is created by compilers

Wubin Ouyang
  • 777
  • 1
  • 7
  • 9