explanation on simple c++ inheritance -
#include <iostream> using namespace std; class { public: void m1(){ cout << 'a'; } virtual void m2(){ cout << 'b'; } virtual void m3(){ cout << 'c'; } }; class b: public { public: void m1(){ cout << 'd'; } void m2(){ cout << 'e'; } }; class c: public b { public: void m3(){ cout << 'f'; } }; int main() { cout << "hello world!" << endl; a* = new b(); a->m1(); a->m2(); a->m3(); return 0; } what output? thought "d e c" after running program "a e c"
could 1 elaborate going on behind line of code:
a* = new b();
virtual member functions dispatched based on dynamic (run-time) type of object. non-virtual member functions dispatched based on static (compile-time) type of object.
a *a = new b(); a points object dynamic type b. static type of a a*, however, means static type of *a a.
virtual functions (m2 , m3) dispatched based on dynamic type, b::m2 , b::m3 called.
non-virtual functions dispatched based on static type. static type of *a a, a::m1 called.
what going on in new line? new object of type b created dynamically, , new expression returns pointer object (of type b*). then, derived-to-base conversion applied pointer convert a*, used initialise variable a.
in pseudo-code, showing intermediary steps:
b *tmp_b = new b(); // allocate , initialise b object *tmp_a = convert_derived_to_base(tmp_b); *a = tmp_a;
Comments
Post a Comment