38
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)

Georg Fritzsche
  • 97,545
  • 26
  • 194
  • 236
vandanak
  • 1,122
  • 3
  • 11
  • 13
  • 2
    the obvious question is *why*? what is the need for it? may be there are alternate ways to solve that problem. – Naveen Sep 13 '10 at 08:36
  • 1
    You (usually) shouldn't use public data members anyway and go for accessors instead - thus you shouldn't even have a need for this. – Georg Fritzsche Sep 13 '10 at 08:39
  • or to rephrase this a bit: what could you do with virtual 'data members' (fields) what you could not do with non-virtual data members ? – Andre Holzner Sep 13 '10 at 08:43
  • 1
    provided we know what is 'virtual data member' (nausea) – Chubsdad Sep 13 '10 at 08:52
  • 2
    Please add the word `virtual` somewhere in your pseudocode. – Potatoswatter Sep 13 '10 at 09:10
  • 5
    @Georg: Nonsense, public data members have their place. – John Dibling Sep 13 '10 at 16:26
  • @John: Thus *"usually"* - structs carrying only a bit of data are the obvious exception in C++. With polymorphism coming into play i can't see where public data members might be useful. – Georg Fritzsche Sep 13 '10 at 20:56
  • 2
    @andre: Just an idea: Virtual data members could be used for mixins or duck typing. When 2 classes `A` and `B` both define a `virtual int count`, then a derived class which inherits A and B could carry only a single (as it is virtual) `count` member. For this the base-classes either need to have a compatible layout or the compiler could automatically create getter/setters which synchronize the value for both base classes. – Tino Jan 25 '14 at 20:24
  • See also https://stackoverflow.com/questions/20872638/is-there-a-way-to-make-a-virtual-variable-in-a-c-base-class and https://stackoverflow.com/questions/3248255/why-doesnt-c-have-virtual-variables and https://stackoverflow.com/questions/57053057/like-virtual-function-can-we-make-a-variable-virtual-in-c – Richard Chambers May 05 '21 at 17:19

9 Answers9

37

virtual is a Function specifier...

From standard docs,

7.1.2 Function specifiers Function-specifiers can be used only in function declarations. function-specifier: inline virtual explicit

So there is nothing called Virtual data member.

Hope it helps...

Sudip Ghimire
  • 677
  • 6
  • 15
liaK
  • 11,422
  • 11
  • 48
  • 73
  • Ya.. it helped. Went through "http://publib.boulder.ibm.com/infocenter/comphelp/v7v91/index.jsp?topic=/com.ibm.vacpp7a.doc/language/ref/clrc03cplr099.htm" as well... – vandanak Sep 13 '10 at 11:03
  • 6
    What about virtual inheritance? `class Foo : public virtual Bar` doesn't seem like a function declaration to me... – tomi.lee.jones Jun 12 '15 at 14:24
17

No, but you can create a virtual function to return a pointer to what you call virtual data member

mmonem
  • 2,811
  • 2
  • 28
  • 38
6

No, in C++ there are no virtual data members.

Naveen
  • 74,600
  • 47
  • 176
  • 233
2

I think not, but you might simulate it using virtual getters and setter perhaps?

Ronny Brendel
  • 4,777
  • 5
  • 35
  • 55
2

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

That is not correct. We make virtual functions to allow derived classes to provide different implementation from what the base provides. It is not used to identify that the base class pointer is pointing to derived class.

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

Only non static member functions can be virtual. Data members can not be.

Here's a link with some more info on that

Chubsdad
  • 24,777
  • 4
  • 73
  • 129
  • 3
    "We make virtual functions to allow derived classes to provide different implementation from what the base provides." Not quite, you already get that when you create a derived class and write a function with the same name as one in a superclass. What `virtual` does is allow you to cast an object to one of its superclasses but still use the derived class's implementation for virtual functions. (In other words, C++ uses static dispatch for normal functions and dynamic dispatch for virtual ones.) – JAB Nov 20 '13 at 16:30
2

No, because that would break encapsulation in a myriad of unexpected ways. Whatever you want to achieve can be done with protected attributes and/or virtual functions.

Besides, virtual functions are a method of dispatch (i.e. selecting which function is going to be called), rather than selecting a memory location corresponding to the member attribute.

Igor Zevaka
  • 74,528
  • 26
  • 112
  • 128
  • 1
    Could you please provide an example or two where this would be a problem (and that is not a problem of diamond inheritance already)? I've been wondering about the reasons of this decision. – The Vee Mar 09 '18 at 08:34
1

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
1

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.

Keith
  • 49
  • 5
0

Maybe you can see the problem in a equivalent way:

class VirtualDataMember{  
    public:  
    ...
}

class DerviedDataMember: public VirtualDataMember{  
    public:  
    ... 
}

class Base{  
    public:  
        VirtualDataMember* dataMember;
        void counter();     
        ...  
}
Willi Mentzel
  • 27,862
  • 20
  • 113
  • 121
Mauro
  • 1