What is the purpose of Virtual member in C++? [closed]
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.
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).
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;
}
精彩评论