Override/override of member variables inherited in C ++

Source: Internet
Author: User

First, you need to understand:

(1) Coverage of member functions: the Child class must overwrite the member functions of the parent class. The function names, parameters, and return values must be consistent (of course, the compiler determines );

(2) Coverage of member variables: the Child class only covers the inherited member variables and does not change the variables in the original parent class;

(3) constructor starts from the base class. variables of the same name of each class are not overwritten and are independent variables. Subclass calls the proximity principle. If the parent class has an interface, it will give priority to calls. If the parent class does not exist, it will call the grandfather class interface. Of course, if you have a parent class, it will first call its own function;

Let's first look at a program:

# Include "stdafx. H "# include <iostream >#include <string> using namespace STD; Class A {public: int m; A () {M = 1; printf (". M = % d \ n ", this-> m);} void print () {printf (" % d \ n ", this-> m );}}; class B: Public A {public: int m; B () {m = 2; printf ("B. M = % d \ n ", this-> m) ;}}; int _ tmain (INT argc, _ tchar * argv []) {B; B. print (); printf ("% d \ n", B. m); Return 0 ;} /// ==================================================== output a. M = 1b. M = 212

 

That is to say, during the call process, the program first constructs a base class, sets m in a to 1, then constructs a subclass, sets m in B to 2, and then calls B. print (); in this case, the m values in A and B are 1 and 2. B searches for the print function in Class B and finds that the function does not exist, and then searches for the function in its parent class, output B. m, so is m a member function in Class A or Class B? Of course, it is a member variable in Class A. Why?

Let's see what C ++ primer says?

 

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.