Question

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.

Was it helpful?

Solution 2

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.

OTHER TIPS

NO, you cannot.

But instead, just make a virtual get/set.

Maybe this is something what you want:

#include <iostream>

class AbstractSomething
{
public:
    void add(int diff){ data() += diff; };
    int get() const { return data(); }
protected:
    virtual int & data() = 0;
    virtual int const & data() const = 0;
};

class ConcreteSomething
  : public AbstractSomething
{
public:
    ConcreteSomething() { m_data = 0; }
protected:
    virtual int & data() { return m_data; }
    virtual int const & data() const { return m_data; }
private:
    int m_data;
};

int main()
{
    ConcreteSomething c;
    c.add(7);
    c.add(3);
    std::cout << c.get() << std::endl;
    return 0;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top