C ++ note masking inheritance

Source: Internet
Author: User

Let's look at an example:

Class base {public: Virtual void mf1 () = 0; virtual void mf1 (INT) {} virtual void mf2 () {} void mf3 () {} void mf3 (double) {}}; class derived: public base {public: Virtual void mf1 () {}void mf3 () {} void mf4 (){}};

The behavior of this code will surprise every C ++ programmer who is facing it for the first time, all functions named mf1 and mf3 in base class are hidden by mf1 and mf3 functions in derived class. From the perspective of name search, base: mf1 and base: mf3 are no longer inherited by derived!

Derived D; int X; D. mf1 (); D. mf1 (x); // error! Because derived: mf3 hides base: mf1d. mf2 (); D. mf3 (); D. mf3 (x); // error! Because derived: mf3 hides base: mf3

The above behavior violates the is-a relationship between base and derived class, so you almost always have to overturn C ++'s default masking behavior for "inherited names. You can use the using declarative method to achieve the goal:

Class derived: public base {public: using base: mf1; // set the using base: mf3 of mf1 and mf3 in the base class; // all objects are visible in the derived scope. Virtual void mf1 () {} void mf3 () {} void mf4 (){}};

Note:

One of the most important rules for Object-Oriented Programming with C ++ is that public inheritance (Public inheritance) implies a "is-a" (yes) relationship.

From Objective C ++

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.