0

i'm new to c++, i'm learning dynamic polymorphism. But i'm getting really confused in the details. can anyone explain why we use virtual, override and use pure virtual functions even though we can just overload methods??

Thanks

default-303
  • 361
  • 1
  • 4
  • 15
  • A quick google for "explanation polymorphism beginner c++" will turn up numerous links with explanations designed to suit beginners. – Peter Jul 18 '20 at 08:45
  • Does this answer your question? [Why do we need virtual functions in C++?](https://stackoverflow.com/questions/2391679/why-do-we-need-virtual-functions-in-c) – ChrisMM Jul 21 '20 at 14:22

2 Answers2

0

Look at this code:

class Base
{
    public:
    void my_method() { std::cout << "base" << std::endl; }
};

class Derived : public Base
{
    public:
    void my_method() { std::cout << "derived" << std::endl; }
};

int main()
{
    Base* object = new Derived;
 
    object->my_method();
 
    delete object;

    return 0;   
}

Implemented: http://www.cpp.sh/4z4p

The output of this is "base", despite object being constructed as Derived. Add a virtual in front of Base::my_method and this changes. Add an override to Derived::my_method and it won't compile should it not actually override.

Note that while here things are easy and clear, later on you have more complicated cases and you might think that you override while you actually don't. For example, you might change the signature of the method in the base class while forgetting to change it in the subclass, or the other way around.

Pure virtual methods are to show that something is to be implemented. The idea is that you create an interface which only determines what a set of classes is supposed being able to do but which does not do anything by itself. A pure virtual class, that is. In Java, interface is actually be a keyword on it's own.
If your base has a pure virtual method and your subclass does not implement it, your compiler will result in error, which is useful.

One thing not in your list but still somewhat useful is the keyword final with which you disallow deriving a class, essentially the opposite of an interface.

Aziuth
  • 3,652
  • 3
  • 18
  • 36
0

overloading functions means having the same function name with a different signature - i.e. different parameters and/or return type.

int test(int a)
void test();

here, int test(int a) is an overload of void test().

virtual only exists in the context of inheritance. it means "Hey, this function can be overriden in subclasses".

override is just a hint that you actually intend to override a virtual function.

pure virtual functions look like this:

void virtualFunction() = 0;

and means that this function is abstract (in C# and Java terms), i.e. it does not contain an implementation in this class, but is meant to be overriden in one of it's subclasses. Infact you cannot instantiate a class with a non-overriden pure virtual function.

Raildex
  • 3,406
  • 1
  • 18
  • 42