-2

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.

Mark
  • 8,408
  • 15
  • 57
  • 81
  • 3
    Safety? How does making a function virtual affect safety? Also, isn't this just a duplicate of [this question?](http://stackoverflow.com/questions/1306778/c-virtual-pure-virtual-explained) – Nicol Bolas Jul 10 '11 at 02:49

2 Answers2

3

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

Jerry Coffin
  • 476,176
  • 80
  • 629
  • 1,111
2

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;
}
Maxpm
  • 24,113
  • 33
  • 111
  • 170