Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inherit from const class

I would like to inherit from a class with the const specifier like this:

class Property
{
    int get() const;
    void set(int a);
};

class ConstChild : public const Property
{
    // Can never call A::set() with this class, even if
    // the instantiation of this class is not const
};

class NonConstChild : public Property
{
    // Can call both A::set() and A::get() depending on 
    // the constness of instantiation of this class
};

My compiler obviously gives me an error for the const keyword in the second classes declaration. Ideally I'd like to avoid having to create a new class ReadOnlyProperty from which ConstChild would inherit.

Can I somehow use the const keyword for inheritance?

  • If not, do you have any other ideas on how to solve this problem?
like image 445
Martin Darterson Avatar asked Jun 28 '16 21:06

Martin Darterson


2 Answers

Introduce mutability later in your inheritance tree and derive appropriately:

class Property
{
    int get() const;
};
class MutableProperty : public Property {
{
    void set(int a);
};

And then:

class ConstChild : public Property { ... };
class MutableChild : public MutableProperty { ... };
like image 131
Thomas B Preusser Avatar answered Sep 18 '22 10:09

Thomas B Preusser


I had the need for a related problem, which is: to really control/highlight mutable and const access on some class. I did it with this simple reusable template wrapper:

template <typename T>
class TAccessor : private T
{
public:
    const T&    Const() const { return *this; }
    T&          Mutable() { return *this; }
};

// Example of use:
template <typename T>
using MyVector = TAccessor<std::vector<T>>;


void main()
{
    MyVector<int> vector;

    vector.Mutable().push_back(10);

    int x = vector.Const()[1];
    ...
}
like image 20
Philippe Avatar answered Sep 22 '22 10:09

Philippe