views:

139

answers:

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

+1  A: 

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

mmonem
+1  A: 

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

Ronny
+4  A: 

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

Naveen
Can you back the claim up?
doron
+1  A: 

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
+2  A: 

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

liaK
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...
A: 

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