Turning an impure virtual function into a pure one 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 

In this deal, I will have ClassA and ClassC objects grouped into containers and repeating. ClassA has an unclean virtual function to perform this iteration, but it is empty using only {} ; that is, it is empty, available only if iteration occurs with ClassC , in which case it is called, otherwise it does nothing. I cannot be clean, otherwise I cannot have ClassA objects.

But to ensure that ClassC really implements this function, forcing the user of this class to do this, I make this function pure virtual in ClassB .

It is acceptable? Nothing will break if I take an unclean virtual function, make it clean, and then make it ClassC again in ClassC ?

+4
source share
2 answers

You are fine if you are presented in your explanations. 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 only be used as the base class of some other class; no objects of an abstract class can be created, except subobjects of a class derived from it. A class is abstract if it has at least one pure virtual function. [Note: such a function may be inherited: see below. - final note]. A virtual function is specified as pure, using pure-specifier (9.2) in the function declaration in the function declaration. A pure virtual function should be defined only when called with or, as if with (12.4), the syntax of a qualified identifier (5.1)

The β€œbelow” mentioned above leads to this note:

C ++ 11 Β§ 10.4p5

[Note. An abstract class can be obtained from a class that is not abstract, and a pure virtual function can override a virtual function that is not pure. - final note]

+3
source

an unclean virtual function is present in ClassA but not implemented;

This results in a linker error. When creating ClassA objects or its subclasses, all virtual methods must be implemented. For pure virtual methods only, the body of the method is optional.

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

Yes, this is the right way. But, you should also appreciate this, is it worth having a new class to make sure that several methods are implemented or not?
For C ++ 11, you might think of cleverly using the override identifier.

In addition, you should not worry about the internal details of vtable , as they are defined in the implementation.

0
source

Source: https://habr.com/ru/post/1481148/


All Articles