Accessibility of virtual functions

Source: Internet
Author: User
 

First, let's look atCode:

 
# Include <iostream> using namespace STD; class base {public: Virtual void fun () {cout <"base" <Endl ;}}; class son: public base {public: void fun () {cout <"son" <Endl ;}}; void DIS (base & S) {S. fun () ;}int main () {base A; DIS (a); son s; DIS (s); Return 0 ;}

Output: No problem with base son

If the following code is used:

# Include <iostream> using namespace STD; class base {public: Virtual void fun () {cout <"base" <Endl ;}}; class son: public base {PRIVATE: // modify void fun () {cout <"son" <Endl ;}}; void DIS (base & S) {S. fun () ;}int main () {base A; DIS (a); son s; DIS (s); Return 0 ;}

The virtual function is declared as private in the subclass, but the result is still the above and there is no compilation error.

Next:

 
# Include <iostream> using namespace STD; class base {public: Virtual void fun () {cout <"base" <Endl ;}}; class son: private base // {public: // note that public void fun () {cout <"son" <Endl ;}}; void DIS (base & S) {S. fun () ;}int main () {base A; DIS (a); son s; DIS (s); Return 0 ;}

Compilation error, Main. cpp: 29: 10: Error: 'base' is an inaccessible base of 'son'

It can be seen that the accessibility of the virtual functions in the derived class is related to the Inheritance Method and the declaration method (public or private) of the virtual functions in the base class) it has nothing to do with the method declared by the derived class (such as public inheritance, but declared as private, but still accessible)

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.