简体   繁体   中英

constructor in inherited class?

I'm learning about class inheritance in C++ and read the following:

When constructing a derived class, its base class part is constructed first. The order of operations is:

1) The base class members are constructed

2) The base class constructor code is called

could someone explain the difference between 1 and 2? How could the base class members being constructed without calling the base class constructor? isn't that the constructor's job?

Before trying to understand derived class construction, you should understand class construction. How is a class constructed? When constructing a class, its data members are constructed first. The order of execution within the constructor is:

  1. The class members are constructed.
  2. The constructor body is called.

How could the class members be constructed without calling the constructor? They aren't, as that is part of the constructor's job. The constructor is called, at which point the constructor constructs the class members, then the constructor executes its body (called its "code" in whatever you are reading).

MyClass::MyClass()   // <-- entry point for the constructor
                     // <-- construct members
{ /* do stuff */ }   // <-- the body/code

You can control member construction via an initialization list or you can fall back on default construction for the members.


Ready for inheritance? The only addition is that the base class is added to the beginning of the initialization list.

Derived::Derived()   // <-- entry point for the derived class constructor
                     // <-- construct base class (see below)
                     // <-- construct members
{ /* do stuff */ }   // <-- the body/code
Base::Base()         // <-- entry point for the base class constructor
                     // <-- construct members (a.k.a. step 1)
{ /* do stuff */ }   // <-- the body/code (a.k.a. step 2)

More complex, but basically the same thing as before.

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