What's the reason for while using reserved word virtual before functions? Basically desire a child class to override a parent or gaurdian function, I simply declare exactly the same function for example "void draw()".

class Parent

class Child : public Parent 

int primary()



The output is 2.

So again, why would the reserved word "virtual" be necessary within the header of say() ?

Thanks a lot.

If the function were virtual, then you may do that but still obtain the output "2":

Parent* a = new Child()

a->say()

This is guaranteed as a virtual function uses the actual type whereas a non-virtual function uses the declared type. Educate yourself on polymorphism for any better discussion of why you'd do.

Check it out with:

Parent *a = new Child()

Parent *b = new Parent()

a->say()

b->say()

Without virtual, both with print '1'. Add virtual, and also the child will behave like a young child, despite the fact that it's being known to using a pointer to some Parent.

If you don't make use of the virtual keyword you aren't overriding, but rahter determining an unrelated method within the derived class which will hide the bottom class method. That's, with no virtual, Base::say and Derived::say are unrelated --aside from the title coincidence.

If you use the virtual keyword (needed within the base, optional within the derived class), you're telling the compiler that classes that be a consequence of this base will have the ability to override the technique. For the reason that situation, Base::say and Derived::say are thought overrides of the identical method.

If you use a reference or pointer to some base class to call an online method, the compiler will prove to add the right code to ensure that the final overrider is known as (the override within the most derived class that defines the technique within the hierarchy from the concrete instance being used). Observe that if you don't use references/pointer but local variables, the compiler can resolve the phone call also it need not make use of the virtual dispatch mechanism.

If you use the keyword virtual, an online function table is produced to discover the right techniques within an instance. Then, even when the derived instance is pointed to with a base class pointer, it'll still find the appropriate implementation from the method.