C++ Logo

std-discussion

Advanced search

Decouple constness for inherited interfaces

From: Lior Lahav <lahavlior_at_[hidden]>
Date: Sat, 21 Sep 2019 06:50:56 +0300
Hello,

The following is a short introduction of a potential proposal.

Please share any thoughts if any.


Allowing to decouple const correctness when using inheritance


Motivation:

the following example doesn't compile since getName() is a const method and
cannot mutate member fields.

class Base{

public:

               virtual std::string getName() const = 0;

};
class Derived : public Base {
public:
               std::string getName() const override
               {
                              if (mCachedName.empty() == true)
                                             mCachedName = "Derived";

                              return mCachedName;
               }
private:
               std::string mCachedName;
};



The transitive behavior of c++ constness starting in Base class is forcing
the method in the derived class to be const as well.

Declaring mCachedName as mutable to solve the issue makes the code less
safe by allowing all other const methods to change the variable and at the
same time complicates readability and context, it appears to be more of a
workaround than a proper solution.

It would be logical that a pure abstract class const correctness would be
decoupled from an implementation and should not dictate whether derived
class should have side effects.



Proposal.

Introducing the 'mutable' keyword to the end of the method deceleration
indicating that the method may invoke side effects.

 e.g.* std::string getName() mutable override*

 Mutable in this context will override a matching method signature in the
base class while ignoring const correctness and can be used only if the
Base class doesn't implement both the const and the non-const versions of a
method.

 In addition it allows to declare all base interface methods as const,
removing any potential compilation errors when a user is calling on a const
instance.

Received on 2019-09-20 22:56:33