Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Turning a non-pure virtual function into pure in a subclass

So, I have this polymorphic hierarchy:

ClassA
Is not abstract, no pure virtual functions, but a few virtual functions

ClassB:public ClassA
Defines an extended interface for a certain type of subclass; 
 is abstract with pure virtual functions

ClassC:public ClassB
Usable class, no more subclassing

Here's the deal, I will have objects of ClassA and ClassC thrown together into containers and iterated through. To perform this iteration, a non-pure virtual function is present in ClassA but is empty with just {}; that is, it is empty, made available only if the iteration encounters a ClassC in which case it is invoked, otherwise it does nothing. I can't have it be pure otherwise I cannot have objects of ClassA.

But to ensure that ClassC does in fact implement that function, forcing the user of that class to do so, I make this function pure virtual in ClassB.

Is this acceptable? Nothing will "break" if I take a non-pure virtual function, make it pure, then make it non-pure again in ClassC ?

like image 976
johnbakers Avatar asked May 16 '13 10:05

johnbakers


1 Answers

You're fine if implemented as you present in your explanation. Without going into entire sections on abstract base classes and virtual functions, the standard dictates:

C++ § 10.4p2

An abstract class is a class that can be used only as a base class of some other class; no objects of an abstract class can be created except as subobjects of a class derived from it. A class is abstract if it has at least one pure virtual function. [ Note: Such a function might be inherited: see below. — end note ] A virtual function is specified pure by using a pure-specifier (9.2) in the function declaration in the class definition. A pure virtual function need be defined only if called with, or as if with (12.4), the qualified-id syntax (5.1)

The "below" referenced above leads to this note:

C++11 § 10.4p5

[Note: An abstract class can be derived from a class that is not abstract, and a pure virtual function may override a virtual function which is not pure. - end note]

like image 72
WhozCraig Avatar answered Oct 30 '22 00:10

WhozCraig