I don't see the purpose of a virtual member in a class other than safety. Are there any other reasons to use virtual when designing implementations? Edit: I erased the variable part.
2 Answers
There is no such thing as a virtual variable, only a virtual function or virtual inheritance. As such, lack of a purpose for such a thing seems like rather a good thing.
Edit: Virtual functions are how C++ implements run-time polymorphism. Trying to explain the uses/purposes of polymorphism is probably a bit beyond what will fit into a reasonable-sized post. The general idea, however, is that you can define some type of behavior in a base class, then implement that behavior differently in each derived class. For a more practical example than most, consider a base database
class that defines things like finding a set of records that fit some criteria. Then you can implement that behavior one way with a SQL database (by generating SQL), and another with, say, MongoDB. The implementation for one will be quite a bit different from the other, but viewed abstractly they're still both doing the same basic things (finding/reading/writing records).

- 476,176
- 80
- 629
- 1,111
-
Really? I don't understand why there should exist something that is useless. – Mark Jul 10 '11 at 02:42
-
@Mark: nor do I. My point was that since there's no use for them, the fact that they don't exist is no real loss. – Jerry Coffin Jul 10 '11 at 02:48
I shall answer... In code!
#include <string>
struct Base
{
// virtual int MemberVariable; // This is not legal C++. Member variables cannot be virtual.
virtual ~Base() {} // Required for polymorphism.
std::string NotVirtual()
{
return "In Base.";
}
virtual std::string Virtual()
{
return "In Base.";
}
};
struct Derived: public Base
{
std::string NotVirtual()
{
return "In Derived.";
}
std::string Virtual()
{
return "In Derived.";
}
};
int main()
{
Base* BasePointer = new Derived;
std::string StringFromBase = BasePointer->NotVirtual(); // "In Base.";
std::string StringFromDerived = BasePointer->Virtual(); // "In Derived."
delete BasePointer;
return 0;
}

- 24,113
- 33
- 111
- 170
-
-
@Mankarse Sorry, that's my typo. It was left over from a more verbose "first draft." – Maxpm Jul 10 '11 at 03:43
-
-
In that case this answer has undefined behaviour. Base must have a virtual destructor. – Mankarse Jul 10 '11 at 03:45