C++ Core Guidelines: The Remaining Rules to Class Hierarchies

I needed three posts to present the 20 rules for class hierarchies in the C++ core guidelines. Here are the seven remaining rules.

 To get the great picture. These are all special rules for class hierarchies.

hierarchy

 Let's continue with rule C.134. 

C.134: Ensure all non-const data members have the same access level

The previous rule C.133 stated that you should avoid protected data. This means that all of your non-const data members should be either public or private. An object can have data members that  and do not prescribe the invariants of the object. Non-const data members that do not prescribe the invariants of an object should be public. In the contrast, non-const private data members are used for the object invariants. To remind you: a data member having an invariant cannot have all values of the underlying type.

If you think about class design more general, you will recognise two kinds of classes.

  • All public: classes with only public data members because the data members have no invariant. Honestly, you should use a struct.
  • All private: classes with only private data member or const data members that established the invariant.

Based on this observation, all your non-const data members should either be public or private.

Imagine if you have a class with public and non-constant invariants. This means that you have to maintain the invariance of the data-members through the whole class hierarchy. This is quite error-prone because you can not easily control the invariants of your class. Or to say it differently. You break encapsulation.

C.135: Use multiple inheritance to represent multiple distinct interfaces

It is a good idea that your interfaces will only support one aspect of your design. What does that mean? If you provide a pure interface consisting only of pure virtual functions a concrete class has to implement all functions. This means in particular in case of a too rich interface, the class has to implement functions it doesn't need or make no sense.

An example of two distinct interfaces is istream and ostream from the input and output streams library.

class iostream : public istream, public ostream {   // very simplified
    // ...
};

 

By combining both interfaces istream for input operations and ostream for output operations we can quite easily create a new interface.

C.136: Use multiple inheritance to represent the union of implementation attributes, C.137: Use virtual bases to avoid overly general base classes

Both rules are quite special. Therefore I will skip them. The guidelines said that C.137 is relatively seldom used and that C.138 is similar to C. 129: When designing a class hierarchy, distinguish between implementation inheritance and interface inheritance.

C.138: Create an overload set for a derived class and its bases with using

This rules is quite obvious and holds for virtual and non-virtual functions. If you don't use the using declaration then member functions in the derived class hide the entire overload set. Sometimes this process is called shadowing. Breaking this rules is often quite confusing.

An example from the guidelines makes this rule quite clear.

class B {
public:
    virtual int f(int i) { std::cout << "f(int): "; return i; }
    virtual double f(double d) { std::cout << "f(double): "; return d; }
};
class D: public B {
public:
    int f(int i) override { std::cout << "f(int): "; return i + 1; }
};
int main()
{
    D d;
    std::cout << d.f(2) << '\n';   // prints "f(int): 3"
    std::cout << d.f(2.3) << '\n'; // prints "f(int): 3"
}

 

Look at the last line. d.f(2.3) with a double argument is called but the int overload of class D is used; therefore, a narrowing conversion from double to int happens. That is most of the time, not the behaviour you want. To use the double overload of class B, you have to introduce it in the scope of D.

 

class D: public B {
public:
    int f(int i) override { std::cout << "f(int): "; return i + 1; }
    using B::f; // exposes f(double)
};

 

C.139: Use final sparingly

 final is a new feature with C++11. You can use it for a class or for a virtual function.

  • If you derive a class My_widget final from a class Widget, you cannot further derive a class from My_widget.
class Widget { /* ... */ };

// nobody will ever want to improve My_widget (or so you thought)
class My_widget final : public Widget { /* ... */ };

class My_improved_widget : public My_widget { /* ... */ };  // error: can't do that

 

  • You can declare a virtual function as final. That means you can not override the function in derived classes.
struct Base
{
    virtual void foo();
};
 
struct A : Base
{
    void foo() final; // A::foo is overridden and it is the final override
};
 
struct B final : A // struct B is final
{
    void foo() override; // Error: foo cannot be overridden as it's final in A
};

 

If you use final, you seal your class hierarchy on a class base or on a virtual function base. Often that has consequences you can not oversee. The potential performance benefit of using final should be your second thought.

C.140: Do not provide different default arguments for a virtual function and an overrider

Not following this rule can cause a lot of confusion. Have a look.

// overrider.cpp

#include <iostream>

class Base {
public:
    virtual int multiply(int value, int factor = 2) = 0;
};

class Derived : public Base {
public:
  int multiply(int value, int factor = 10) override {
    return factor * value;
  }
};

int main(){

  std::cout << std::endl;

  Derived d;
  Base& b = d;

  std::cout << "b.multiply(10): " << b.multiply(10) << std::endl; 
  std::cout << "d.multiply(10): " << d.multiply(10) << std::endl;  

  std::cout << std::endl;

}

 

 Here is the quite surprising output of the program.

overrider

What's happening? Both objects b and d call the same function because the function is virtual and, therefore, late binding happens. This will not hold for the data such as the default arguments. They are statically bound and early binding happens.

What's next?

Now we are done with the design of class hierarchies. The question remains: who can we access the objects in the class hierarchy. Of course, I will answer this question in the next post.

 

 

Thanks a lot to my Patreon Supporters: Eric Pederson and Paul Baxter.

 

Get your e-book at leanpub:

The C++ Standard Library

 

Concurrency With Modern C++

 

Get Both as one Bundle

cover   ConcurrencyCoverFrame   bundle
With C++11 and C++14 we got a lot of new C++ libraries. In addition, the existing ones are greatly improved. The key idea of my book is to give you the necessary information to the current C++ libraries in about 200 pages.  

C++11 is the first C++ standard that deals with concurrency. The story goes on with C++17 and will continue with C++20.

I'll give you a detailed insight in the current and the upcoming concurrency in C++. This insight includes the theory and a lot of practice with more the 100 source files.

 

Get my books "The C++ Standard Library" and "Concurrency with Modern C++" in a bundle.

In sum, you get more than 500 pages full of modern C++ and more than 100 source files presenting concurrency in practice.

 

Add comment


My Newest E-Books

Latest comments

Subscribe to the newsletter (+ pdf bundle)

Blog archive

Source Code

Visitors

Today 42

All 506508

Currently are 150 guests and no members online