Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why in C++ 'virtual' and '=0' is both needed to describe a method is abstract?

As it is explained in The C++ programming language:

virtual void push(char c) = 0;
virtual void pop() = 0;

The word virtual means 'may be redefined later in a class derived from this one'
The =0 syntax says that some class derived from Stack must define the function.

So why =0 symbol is needed? Does it means that a derived class must define this function, and that's to say when there is no =0, some derived classes are not forced to define this method?

I'm confusing about this, need some help.

like image 694
hwding Avatar asked Sep 02 '16 09:09

hwding


1 Answers

Your thoughts were right.

So why =0 symbol is needed? Does it means that a child class must define this function, and that's to say when there is no =0, some child classes are not forced to define this method?

Basically you can:

  • Make a method non-virtual

This doesn't allow any class deriving from the class that implements the method (through either public or protected) to change the method's behavior.

  • Make a method virtual

This allows (but doesn't enforce) any class deriving from the class that implements the method (through either public or protected) to change the behavior of the method in the base class. You don't even have to call the original base class method anymore so you can make severe changes if needed.

  • Make a method pure virtual ( virtual = 0 )

This enforces that any class deriving from the class that implements the method (through either public or protected) to implement some kind of behavior/body for this method. If the deriving class does not provide an implementation then this class will instantly become abstract itself. This allows to omit the behavior/body of the method in the base class and because of this it is not allowed to directly instantiate a class that has one or more pure virtual methods (abstract class).

like image 116
Hatted Rooster Avatar answered Sep 21 '22 10:09

Hatted Rooster