Virtual function access Rights after C + + inheritance

Source: Internet
Author: User

Today, when writing code, I find that the access to the inherited function is not very clear, so I made a test:

1. Header file (test.h) 1 #include <iostream> 2 using namespace std;

3 4 classa{5 Private:6 voidprint () {7cout <<"This is A"<<Endl;8  }9 };Ten  One classB: Publica{
};

A is a base class and B is a subclass of a.

2. source Files (test.cpp)

1 " test.h " 2 3 void Main () 4 {  5     New B (); 6     pb->print (); 7 8     GetChar (); 9     GetChar (); Ten }

Because B inherits the function print from Class A and inherits the access rights of print at the same time, the compilation does not pass at this time.

3. Modified header file (test.h)

1#include <iostream>2 using namespacestd;3 4 classa{5 Private:6     voidprint () {7cout <<"This is A"<<Endl;8     }9 };Ten  One classB: Publica{ A  Public: -     voidprint () { -cout <<"This is B"<<Endl; the     } -};

Subclass B overrides the print function of a, at which point the compilation succeeds and runs as follows:

4. Summary

When a class inherits from another class, the access permission of the base class member function is the default inherited permission, and if the subclass overrides this function itself, the access permission is changed to the access permission set by the subclass. In short, the function access permissions set by the subclass take precedence over the default access rights of the syntax after inheriting from the base class.

C + + inherited virtual function access rights

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.