C++ difference between virtual = 0; and empty function

The difference is that virtual void aMethod() = 0 is a pure virtual function, meaning that:

  1. SomeClass becomes an abstract base class, meaning it cannot be instantiated.
  2. Any class which inherits from SomeClass must implement aMethod, or it too becomes an abstract base class which cannot be instantiated

Note that any class with one or more pure virtual functions is automatically an abstract base class.


For your

class SomeClass{
   virtual void aMethod()=0;
}

the presence of a pure virtual method makes your class abstract. Once you have one such pure virtual method, =0, in your class, you cannot instantiate the class. What is more, any derived class must implement the pure virtual aMethod(), or it becomes an abstract class as well.

In your derived class, you overwrite the pure virtual method from above, and this makes the derived class non abstract. You can instantiate this derived class.

But, in derived class, method's body is empty, right? That's why your question makes sense: why not make the class pure virtual as well. Well, your class may entail other methods. If so, SomeClass cannot be instantiated (there is a pure virtual method), whereas child class SomeClassSon can be.

Same applies to your AnotherClass, which can be instantiated, contrary to SomeClass.


the declaration aMethod()=0 tells the compiler that this method must be provided for in subclasses. Any subclass that does not implement the method can not be instantiated. This helps you ensure any objects of the base class will have the method implemented.


The "equals 0" you're referring to is called "pure virtual". It's a function that the child that wants to be instantiated HAS to implement as opposed to providing base functionality meaning that the parent class is going to define functionality that has to exist but that the parent has no knowledge of how the child will do it. Note that this makes the class abstract in that it cannot be instantiated. For example I may want to define a "Mammal" class I can inherit from and I want its children to act a certain way - but I can't simply make a "Mammal". Instead I would create a "Giraffe" class and make sure it acts like it's supposed to.

It's also explained at this SO question.

The "Empty" function you're referring to is instead functionality where the function is defined and can be called - but does nothing.