C + + Proverbs: Never redefine an inherited non-virtual function

Source: Internet
Author: User

Let's say I tell you class (class) D is from Class (class) B publicly derived (public inheritance), and in Class (class) B, you have defined a public member function (publicly owned) MF. The parameters and return value types of MF are irrelevant, so let's assume they're all void. In other words, I mean:

class B {
 public:
  void mf();
  ...
};
class D: public B { ... };

You don't even have to know anything about b,d, or MF, given an object x of type D,

D x; // x is an object of type D

You may be very surprised by this,

B *pB = &x; // get pointer to x
pB->mf(); // call mf through pointer

behaves differently from the following code:

D *pD = &x; // get pointer to x
pD->mf(); // call mf through pointer

Because in both cases, you call the member function in Object X, MF. Because both of these situations are the same function (function) and the same object, they behave in the same way, right?

Yes, I should. But it may not, in particular, if MF is non-virtual (non-virtual) and D defines its own version of MF:

class D: public B {
 public:
  void mf(); // hides B::mf; see Item33
  ...
};
pB->mf(); // calls B::mf
pD->mf(); // calls D::mf

The reason for this behavior is that non-virtual functions (non-virtual functions), such as B::MF and D::MF, are statically (statically bound) (see Item 37). This means that because PB is declared as a Pointer-to-b type, even if, as in this example, the PB points to an object of a class that inherits from B, the non-virtual functions (Non-virtual function) invoked via PB is always defined in class B. that one.

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.