简体   繁体   中英

Copy constructor with a parameter as a reference to a derived class

There is the following definition of the copy constructor:

A non-template constructor for class X is a copy constructor if its first parameter is of type X& , const X& , volatile X& or const volatile X&, and either there are no other parameters or else all other parameters have default arguments (8.3.6).

Note, that the definiton isn't concerned with the convertions , but the following program works fine:

#include <iostream>

struct B{ };

struct A : B
{
    A(){ }
    A(const B&){ }
};

B b;
A a = b;


int main(){ }

DEMO

and it produces the output

B()
B()
A(const B&)

It's not clear to me, I expected the program doesn't print A(const B&) , because by the definition A(const B&) is not a copy constructor, therefore one is implictly defined as A::A(const A&) with default initializtion which doesn't produce any side-effect.

Couldn't you clarify what's wrong with that reason?

A a = b;

This would call the conversion constructor of class A.

A(const B&){ }   << This is conversion constructor for class A which defines conversion from B to A

Its same like we declare

A(int i) {}  << Convert int to class A object.

Even if you remove the relationship between class A and B then also it lead to that constructor call.

This is known as a converting constructor (§12.3.1). b is copy-initialized into a and A::A(const B&) is selected to perform the conversion. The result of the conversion is used to direct-initialize a .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM