Parameter list Call Subclass constructor

Source: Internet
Author: User

sometimes, the base class constructor is with parameters, and the subclass constructor is without parameters, as follows:classanimal{ Public: Animal (intWidthintHeight) { This->width = width; This->height =height;}Private:    intwidth, height;};classCat: Publicanimal{ Public: Cat () {cout<<"Init cat"<<Endl;}}; Compile error when building Cat class object: C:\Documents and settings\administrator\ desktop \abc\text1.cpp (104): Error C2512:'Animal': no appropriatedefaultconstructor available solve this problem you should explicitly call the parameter constructor of the base class in the cat's constructor. Because the parameter constructor is defined in the base class, the compiler does not provide a default constructor. (or you can add a constructor without parameters to the base class) This problem will be resolved. Here's how to call the base class with a parameter constructor:classCat: Publicanimal{ Public: Cat (): Animal ( -, $) {cout <<"Init cat"<<Endl;} The argument list calls the subclass constructor usage}; That is, add a colon after the constructor, followed by the constructor of the base class. This method can also be used to initialize constants in a class. Constants are not allowed because members are not allowed to be initialized in the class definition. As shown below:classCat: Publicanimal{ Public: Cat (): Animal ( -, $), Age (2), Islikefish (true) {cout <<"Init cat"<<Endl;}Private:    Const intAge ; Const BOOLislikefish;};

Parameter list Call Subclass constructor

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.