Search code examples
c++virtual

virtual variable in C++?


Is it possible to instead of have a virtual function have a virtual variable?

class B { virtual int fn(); /*virtual int val;*/ };
class D1: public B { virtual int fn() {return 0;}; 
/*int D1::val = 0;*/

class D2: public B { virtual int fn() {return 3;}; 
/*int D2::val = 3;*/

Right now i'm writing b->fn() because I have no idea how to have a virtual variable which I think would be more efficient (b->val). Is it possible in C++? Basically I want to have a const variable instead of a const function pointer in the vtable.


Solution

  • Complier will make an indirection/lookup for virtual methods. This only applies to methods (aka. member functions). This indirection/lookup is not applied in C++ to data members (what you called variables).

    See following picture which may give a better graphical representation: http://www.yaldex.com/games-programming/FILES/05fig07.gif

    So, provide access through [virtual] getter/setter.