c++ - common function in base and derived calling base when called through another base function using a derived object? -


#include <iostream>  using namespace std;  class dissection {   int x;   public:     void test() {      cout<<"test base";    }     void caller(){ test(); } };  class dissectionderived: public dissection {   int x;   public:     void  test(){      cout<< "test derived";       } };  int main( int argc, char ** argv ) {   dissectionderived derived;   derived.caller();   return 0; } 

in code sample above, ouput "test base". way thought was, since derived doesn’t have function named caller invoke base class function, since actual type of object dissectionderived able call test function of dissectionderived class. because overload resolution stops after finds closest test function in base class scope?

if caller function can invoked derived function, why cant part of overload resolution in derived class ?

i have used -cg g++ compiler flag , did obj dump of objectfile, output shown below:

symbol table:  0000000000000000 l    d  .text._zn10dissection4testev   0000000000000000 .text._zn10dissection4testev 0000000000000000 l    d  .text._zn10dissection6callerev 0000000000000000 .text._zn10dissection6callerev 0000000000000000  w    f .text._zn10dissection4testev   000000000000001d _zn10dissection4testev 0000000000000000         *und*  0000000000000000 __gxx_personality_v0 0000000000000000         *und*  0000000000000000 _zst4cout 0000000000000000         *und*  0000000000000000 _zstlsist11char_traitsiceerst13basic_ostreamict_es5_pkc 0000000000000000  w    f .text._zn10dissection6callerev 000000000000001a _zn10dissection6callerev 

c++filt _zn10dissection4testev gives dissection::test()

thanks!

when want "which actual class involved" determine function gets called, function needs marked virtual.

this makes compiler put "virtual function table" part of , derived class.

in other words, make virtual void test(); in base. virtual attribute "inherit", derived class virtual - "safety" can mark override (e.g. void test() override { ... }, ensure compiler gives error if try "override" isn't part of base-class.


Comments

Popular posts from this blog

android - Gradle sync Error:Configuration with name 'default' not found -

java - Andrioid studio start fail: Fatal error initializing 'null' -

html - jQuery UI Sortable - Remove placeholder after item is dropped -