Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I'm now learning C++, the OO side, and I see this all the time:

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

class AnotherClass{
   void anotherMethod(){/*Empty*/}
}

class SomeClassSon : public SomeClass{
   void aMethod(){/*Also Empty*/}
}

what is the difference between the 3 methods? The virtual equals zero, the empty one, and the virtual, since it is inherited, empty one.

Why can't I just make the SomeClassSon method like the father, virtual void equals zero?

like image 856
Afonso Tsukamoto Avatar asked Feb 25 '13 20:02

Afonso Tsukamoto


2 Answers

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.

like image 183
kiriloff Avatar answered Sep 22 '22 03:09

kiriloff


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.

like image 20
Charles Salvia Avatar answered Sep 22 '22 03:09

Charles Salvia