C + +: The default constructor of a derived class and the mechanism by which the copy constructor calls the base class constructor (with program validation)

Source: Internet
Author: User

1. If the base class defines a default constructor with no parameters, the default constructor that the compiler automatically generates for the derived class invokes the default constructor for the base class.

2. If the base class defines a copy constructor, the copy constructor that the compiler automatically generates for the derived class also calls the copy constructor of the base class.

3, if the base class defines a constructor with parameters, the derived class does not define any constructors with parameters, you cannot call the parameter constructor of the base class directly, and the program compiles without passing.

The code is as follows:

#include <iostream>using namespace std;
Base class Game, which defines two constructors and a copy constructor class Game{public:game () {cout<< "constructor: Game () \ n";} Game (const game& game) {cout<< "copy constructor: Game (const game& game) \ n";} Game (int i) {cout<< "game (int i) \ n";}};/ /derived class Chess, no constructors and copy constructors are defined class Chess:public Game{};int main () {Chess ch1; Chess CH2 (CH1);//chess CH3 (1);cout<< "End!"; int I;cin>>i;return 0;}
The results of the operation are as follows:

If you do not comment out the " Chess CH3 (1) "This line, which calls the constructor with parameters directly, will cause an error: there is no constructor "Chess::chess" instance that matches the argument list, so the 3rd conclusion is validated.

C + +: The default constructor of a derived class and the mechanism by which the copy constructor calls the base class constructor (with program validation)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.