简体   繁体   中英

default behaviour of defined copy constructor c++

suppose I define a copy c'tor for a class B that inherits A and has a also member variables. Inside the copt c'tor body I write some code, but in the initiallization list I don't call explicitly to A c'tor(also not to copy c'tor), and not initiallize the member variables.

In this case A default c'tor will be called defaultly before reaching B' copy c'tor body. But what would be with the member variables? would they be initillized with their default c'tor or with their copy c'tor with the arguement object's members (the argument object == given to B copy c'tor).

In addition, if there is calling inside the initiallization list to some members' copy c'tor/c'tor or to Parent class copy c'tor/c'tor - would that behaviour be changed?

I know that in case we don't define explicitly copy c'tor: Parent Class and members copy c'tor's are called.

What should I expect in here?

The base class subobject will be default initialized in that case. See [class.base.init]/8:

In a non-delegating constructor, if a given potentially constructed subobject is not designated by a mem-initializer-id (including the case where there is no mem-initializer-list because the constructor has no ctor-initializer ), then

  • if the entity is a non-static data member that has a brace-or-equal-initializer [..]
  • otherwise, if the entity is an anonymous union or a variant member (9.5), no initialization is performed;
  • otherwise, the entity is default-initialized (8.5).

And a potentially constructed subobject is defined in [special]/5:

For a class, its non-static data members, its non-virtual direct base classes , and, if the class is not abstract (10.4), its virtual base classes are called its potentially constructed subobjects.

If you write a copy-constructor and do not initialize a member variable then it will be default-initialized.

The same applies to base classes, in most ways they are treated the same as member variables.

Here is some sample code that will demonstrate:

#include <iostream>

using namespace std;

struct S
{
    S() { cout << "S()\n"; }
    S(S const &) { cout << "S(S&)\n"; }
};

struct T : S
{
    T() {}
    T(T const &t) {}

    // you have to explicitly write this if you want it 
    // T(T const &t): S(t) {}
    //                ^^^^
};

int main()
{
    T t;
    T u(t);
}

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