Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overriding vs Virtual

What is the purpose of using the reserved word virtual in front of functions? If I want a child class to override a parent function, I just declare the same function such as void draw(){}.

class Parent {  public:     void say() {         std::cout << "1";     } };  class Child : public Parent { public:     void say()     {         std::cout << "2";     } };  int main() {     Child* a = new Child();     a->say();     return 0; } 

The output is 2.

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

Thanks a bunch.

like image 808
anonymous Avatar asked May 28 '10 22:05

anonymous


People also ask

Is overriding and virtual function same?

The virtual keyword can be used when declaring overriding functions in a derived class, but it is unnecessary; overrides of virtual functions are always virtual. Virtual functions in a base class must be defined unless they are declared using the pure-specifier.

Should I use Virtual with override?

So the general advice is, Use virtual for the base class function declaration. This is technically necessary. Use override (only) for a derived class' override.

Can you override without virtual?

You cannot override a non-virtual or static method. The overridden base method must be virtual , abstract , or override . An override declaration cannot change the accessibility of the virtual method. Both the override method and the virtual method must have the same access level modifier.

What is virtual and override in solidity?

Solidity lets developers change how a function in the parent contract is implemented in the derived class. This is known as function overriding. The function in the parent contract needs to be declared with the keyword virtual to indicate that it can be overridden in the deriving contract.


2 Answers

If the function were virtual, then you could do this and still get the output "2":

Parent* a = new Child(); a->say(); 

This works because a virtual function uses the actual type whereas a non-virtual function uses the declared type. Read up on polymorphism for a better discussion of why you'd want to do this.

like image 153
Donnie Avatar answered Sep 19 '22 19:09

Donnie


Try it with:

Parent *a = new Child(); Parent *b = new Parent();  a->say(); b->say(); 

Without virtual, both with print '1'. Add virtual, and the child will act like a Child, even though it's being referred to via a pointer to a Parent.

like image 31
Jerry Coffin Avatar answered Sep 21 '22 19:09

Jerry Coffin