"C + +" C + + self-learning Advanced (6): Inheritance (2)--Continue to advanced

Source: Internet
Author: User

Inheriting classes cannot inherit the constructors and destructors of the base class, and we need to define a new constructor and destructor for the derived class if the derived class requires it.
One, single-inheritance constructors

classperson{protected:    Charname[Ten]; Charsex; Public:    //The Constructor of the base classPerson (CharName[],CharSex ): Sex (Sex) {cout<<"Base class constructor!"<<Endl; strcpy ( This-name,name); }};classStudent:: Publicperson{Private:    intNumber ; Public:    //Constructor of the derived classStudent (intNumberCharName[],Charsex):P Erson (name,sex) {cout<<"Derived class constructor!"<<Endl;  This->number =Number ; }};

This part of the dry:
1. The constructor of the inheriting class can only initialize its own newly defined data, cannot initialize something inherited from the base class, and therefore needs to call the constructor of the base class when defining the constructor of the inheriting class, as in this case:

Student (int number,char name[],char sex):P Erson (name,sex) {...}

2. When defining a derived class object, the constructor of the derived class is run first, but its constructor is linked to the constructor of the base class, so the constructor for the base class is actually first run.

3. If the constructor of the base class is not written in the constructor of the inheriting class, the compilation will fail because the compiler will link to the default base class constructor by default, but this function does not exist.

4. The order of execution is independent of the order of writing, and the constructor of the base class is always executed first.

"C + +" C + + self-learning Advanced (6): Inheritance (2)--Continue to advanced

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.