C ++ base class and derived class

Source: Internet
Author: User

I. Structure

The constructor cannot be a virtual function.

A derived class must first call the constructors of the base class, but cannot directly overwrite the constructors of the base class.

Therefore, You Cannot initialize the base class members in the derived class initialization list.

 


See the following example:


[Cpp]
01. class Base
02 .{
03. public:
04. Base (double dNum)
05.: nBase (1)
06., dBase (dNum)
07 .{
08.
09 .}
10. int ShowNum () {return nBase ;}
11. protected:
12. int nBase;
13. double dBase;
14. private:
15 .};
16.
17.
18. class Derived: public Base
19 .{
20.
21. public:
22. Derived (double dNum)
23.: Base (dNum)
24., nBase (3)
25 .{
26. nBase = 2;
27 .}
28. protected:
29. private:
30 .};
Class Base
{
Public:
Base (double dNum)
: NBase (1)
, DBase (dNum)
{

}
Int ShowNum () {return nBase ;}
Protected:
Int nBase;
Double dBase;
Private:
};
 
 
Class Derived: public Base
{
 
Public:
Derived (double dNum)
: Base (dNum)
, NBase (3)
{
NBase = 2;
}
Protected:
Private:
};
Error C2614: "Derived": Invalid member initialization: "nBase" is not a base or member at nBase (3 ).

 

 

 


 

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.