Diaz
Diaz

Reputation: 987

C++ design principle regarding pure virtual functions?

I have been working on a game program lately. I made a base class called Drawable, indicating something that potentially needs (and can) be drawn onto screen.

Apparently, I derived a lot of classes from Drawable, each having its own implementation of draw() function. Now I have two options, for Drawable:

virtual void draw(param);

and:

virtual void draw(param) = 0;

Now lets take a look at another class, say, Scene, which is likely to hold a bunch of Drawable instances, which are stored in a vector. Polymorphism makes it possible to iteratively call draw() function of each stored object.

So, which way it better in terms of OOP design?

I am new to C++ and always find con/destructors of abstract classes mysterious, especially how they are treated by complier.

To put it simple, instead of an abstract class with some pure virtual function f() = 0, I could have made it as

virtual f(){};

What are the pro/cons of pure virtual functions/abstract classes compared to the way above?

Upvotes: 2

Views: 135

Answers (1)

Cheers and hth. - Alf
Cheers and hth. - Alf

Reputation: 145279

The most important issue is whether the function can have a reasonable default in the topmost declaring class, e.g. doing nothing.

If so, then why not provide the default: that's convenient.

But if not, make it pure virtual. IIRC, in original Smalltalk, instead of declaring a method as something like pure virtual, one let the implementation raise the exception "subclass responsibility". And that's the essence of pure virtual, something that can't be reasonably specified in the base class, but must be defined by each derived class.


A secondary issue is that a pure virtual function prevents direct instantiation of the class, i.e. makes the class abstract. It's secondary because when there is no reasonable default then it's not very meaningful to call the function on an object of the declaring class, so it doesn't matter that it's pure virtual there.

Upvotes: 4

Related Questions