开发者

What is the purpose of Virtual member in C++? [closed]

开发者_开发知识库 It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center. Closed 11 years ago.

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;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜