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?
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 difference is that virtual void aMethod() = 0
is a pure virtual function, meaning that:
SomeClass
becomes an abstract base class,
meaning it cannot be instantiated.SomeClass
must implement aMethod
, or it too becomes an abstract base class which cannot be instantiatedNote that any class with one or more pure virtual functions is automatically an abstract base class.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With