Search code examples
c++virtualvirtual-functions

How is C++ VIRTUAL function not redundant?


Possible Duplicates:
Overriding vs Virtual
How am i overriding this C++ inherited member function without the virtual keyword being used?

I am learning C++ at this moment, but I'm not completely in the dark when it comes to programming languages. Something makes no sense to me. My understanding is that a VIRTUAL function in a class can be overridden in sub-classes. However, isn't that allowed by default? For example:

class Color {
    public:
        void Declare() { std::cout <<"I am a generic color."; }
};

class Purple : public Color {
};

If I create an instance of Purple and then call its Declare function, then it will obviously output the console window "I am a generic color." If I want to override this function in the Purple class, I can simply define it there to produce:

class Purple : public Color {
    public:
        void Declare() { std::cout <<"I am purple."; }
};

This, of course, outputs "I am purple." to the console. If I can override functions by default, then what is the point of having VIRTUAL functions to specifically tell the compiler it can be overridden? Sorry for the dumb question. :/


Solution

  • Virtual functions are useful when dealing with polymorphism. Non-virtual functions are looked up at compile time, so creating a variable of type Color and calling its Declare() method will always result in Color::Declare() being called, even if the object in the variable is a Purple.