0

If I have a derived class that has both const and non-const getters for its data, how do I make them private / protected separately in the derived class?

I tried to "disable" the non-const one and the compiler complains even though it doesn't need the non-const one.

Edit: to be clear, I don't want to disable both "getInt()" functions, only the non-const one. (or the const one, but only one of them)

class Base{

public:

    int i;

    void foo() const;
    void foo();

    const int&  getInt() const;
    int&        getInt();

};

class Derived : public Base{

protected:
    void foo();

    int& getInt();

public:

};

Derived d;
int i = d.getInt(); //error, getInt() is protected
Barry
  • 286,269
  • 29
  • 621
  • 977
AdyAdy
  • 988
  • 6
  • 19
  • 2
    Don't. This violates the Liskov Substitution Principle. Wanting to do this makes `Derived` not actually a `Base` anymore. – Barry Jul 10 '18 at 15:44
  • 1
    Change to `class Derived : private Base`. Then you can make Derived expose whatever member functions to pass through to Base as desired. Doesn't violate Liskov's Substitution Principle. – Eljay Jul 10 '18 at 18:08

1 Answers1

0

You are calling getInt() through an instance of Derived, and its protected implementation of the function jumps in before the implementation of Base. The easiest way to limit the access to the const qualified version of this function is to not shadow it in Derived and declare the instance as const:

const Derived d{};

int i = d.getInt(); /* Works, no getInt() implementation in Derived. */

When it makes sense that every instance of Derived is const qualified, you can restrict the creation of Derived objects:

std::unique_ptr<const Base> createDerived()
{
   return std::make_unique<const Derived>();
}

auto d = createDerived(); /* Pointee is const-qualified. */
int i = d->getInt(); /* Ok again. */
lubgr
  • 37,368
  • 3
  • 66
  • 117
  • Thanks! But what I want is simply disable one specific non-const (or const) function and leave all other constness as it is. – AdyAdy Jul 10 '18 at 15:33
  • As linked in the comments above, this is impossible, hence the suggested workaround. – lubgr Jul 10 '18 at 15:35