Friday, 15 June 2012

c++ - Hide virtual function with non-virtual override -



c++ - Hide virtual function with non-virtual override -

having

#include <iostream> using namespace std; class { public: virtual void foo() { cout << "a" << endl; } }; class b : public { public: void foo() { cout << "b" << endl; } }; class c : public b { public: void foo() { cout << "c" << endl; } }; int main() { c c; b* b = &c; b->foo(); homecoming 0; }

the output c, expected b.

i didn't declare b::foo() virtual modifier, expect function phone call determined static type (no polymorphism).

why c::foo() beingness called?

is possible provide non-virtual function in derived class, hides virtual function in base? signature should derived fellow member function have b->foo() calls it, , not (b->*&a::foo)()

the principle of virtual inheritance of fellow member function is direct consequence of c++ standard:

10.3/2: if virtual fellow member function vf declared in class base of operations , in class derived, derived straight or indirectly base, fellow member function vf same name, parameter-type-list , cv-qualification, , refqualifier (or absence of same) base::vf declared, derived::vf also virtual.

so regardless of level of inheritance, function virtual in classes derived somehow a. there no need set keyword virtual.

the goal of polymorphic approach ensure phone call appropriate function corresponding real idendity of object, regardless fact utilize pointer base of operations or pointer real class of object. why obtain "c" !

in this related question explain trick give impression of removing virtuality @ 1 single level, using multiple inheritance. can done single level (you should class of base of operations pointer).

*by way, write pb->b::foo(); no need of *&.

c++ polymorphism virtual-functions

No comments:

Post a Comment