Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

can a class have virtual data members?

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)

like image 690
vandanak Avatar asked Sep 13 '10 08:09

vandanak


People also ask

Can a data member be virtual?

@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.

Can a class have data members?

A data member may be of any type, including classes already defined, pointers to objects of any type, or even references to objects of any type. Data members may be private or public, but are usually held private so that values may only be changed at the discretion of the class function members.

Can a data member be virtual in C++?

Virtual member functions are declared with the keyword virtual . They allow dynamic binding of member functions. Because all virtual functions must be member functions, virtual member functions are simply called virtual functions.

Can a class have virtual?

They are always defined in the base class and overridden in a derived class. It is not mandatory for the derived class to override (or re-define the virtual function), in that case, the base class version of the function is used. A class may have virtual destructor but it cannot have a virtual constructor.


1 Answers

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...

like image 131
liaK Avatar answered Oct 03 '22 21:10

liaK