can a class have virtual data members?

Viewed 34159
class Base{  
    public:  
        void counter();   
    ....   
}

class Dervied: public Base{  
    public:  
        ....  
}

void main()  
{  
     Base *ptr=new Derived;  
     ptr->counter();  
}

To identify that the base class pointer is pointing to derived class and using a derived member function, we make use of "virtual".

Similarly, can we make derived data members "virtual"? (the data member is public)

9 Answers

A class cannot have a virtual member, see for instance this answer. However, you can have something similar using pointers, inheritance and runtime polymorphism.

In the following snippet I define the prototype for a geometrical shape, that has an area method. The picture class has a member shape* s; and the methods of that shape pointed by s are used by picture::show(). In this setup it is undesirable to have an instance of picture before an actual implementation of a shape has been given, hence we force picture to be abstract by adding a dummy virtual function picture::make_real().

// prototypes
class shape
{
    public:
    virtual double area() = 0; // to be defined later
};
class picture
{
    protected:
    shape* s;
    
    virtual void make_real() = 0; // force picture to be abstract
    
    public:
    picture(shape* ptr):
        s{ptr}
    {}
    
    void show()
    {
        std::cout << s->area() << '\n';
    }
};

Next, we actually implement a shape called square and a picture type square_picture that (literally) has a square shape.

// actual implementation

class square : public shape
{
    double len;
    
    public:
    square(double l):
        len{l}
    {}
     
     double area() override
    {
        return len*len;
    }
};



class square_picture : public picture
{
    void make_real() override {} // square_picture is not abstract
    
    public:
    square_picture(double l):
        picture{new square{l}}
    {}
    
    ~square_picture()
    {
        delete s;
    }
};

The class square_picture can be tested with the following snippet

int main()
{
    square_picture A{2.0};
    A.show();
    
    //picture B{nullptr}; // error: picture is abstract
    return 0;
}

which outputs:

4

I have a base class which uses an array of objects. From that class I derived a new class that uses an array of a different type of object. Both variables have exactly the same name. Virtual member functions were added to both classes to process the arrays. These member functions have no trouble finding the correct variable. The member functions and the variables they use are in a common scope.

The virtual member functions are nearly identical in both classes. Only the type of array changed.

C++ templates could have accomplished the same result.

Related