Inherit from const class

后端 未结 8 1595
不思量自难忘°
不思量自难忘° 2021-01-12 00:24

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

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

class Co         


        
8条回答
  •  生来不讨喜
    2021-01-12 00:57

    I had the same need and I ended up with this quite manual approach :

    class A
    {
    public:
    
        void fooMutable(void) {}
        void fooConst(void) const {}
    };
    
    class B : private A
    {
    public:
    
        using A::fooConst;
        const A& getParent(void) const
        {
            return *this;
        }
    };
    
    void fooParent(const A&) {}
    
    int main(void)
    {
        auto b = B{};
        b.fooConst(); // Ok
        b.fooMutable(); // Fail
        fooParent(b); // Fail
        fooParent(b.getParent()); // Ok
    
        return 0;
    }
    

    Note that the using keyword would not work with overloads const/mutable :

    class A
    {
    public:
    
        void foo(void) {}
        void foo(void) const {}
    };
    
    class B : private A
    {
    public:
    
        using A::foo; // Expose the const and the mutable version
    };
    

    To solve this you could redefine the function yourself and call the parent :

    class B : private A
    {
    public:
    
        void foo(void) const
        {
            A::foo();
        }
    };
    

    It can become pretty time consuming if you're inheriting a large hierarchy, but if it's for a not-so-big class it should be very reasonable and being quite natural for the user.

提交回复
热议问题