2

I have a Base class and derived another class from it. The derived class has a function which takes as an argument const Base& and calls its protected member function. I get an error saying that the function being called is protected in that context. I'd like to know why that happens and can I solve it without making the protected function in base class public.

class Base {
protected:
    void call() const {}
};

class C : public Base {
public:
    void func(const Base& b) {
        b.call();
    }
};

I tried adding using Base::call in the derived class but that didn't help

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
  • 5
    Because `b` is another object. You can only call `public` function in other objects. However if you want to call `call` in `this` object it would be possible. So e.g. `void func() const { call(); }` would be perfectly fine. – Some programmer dude Jan 02 '23 at 11:39
  • 1
    So the question from us now really becomes: Why do you pass `b` as argument? – Some programmer dude Jan 02 '23 at 11:39
  • This is just for the sake of example – Erik Nouroyan Jan 02 '23 at 11:42
  • 1
    If you're only passing `b` as an argument for the sake of example, what's the issue? Don't you have an actual problem that you're trying to solve? – molbdnilo Jan 02 '23 at 12:42
  • See https://stackoverflow.com/a/11634082/485343 and https://stackoverflow.com/a/4672888/485343 – rustyx Jan 02 '23 at 12:47
  • 1
    Class C can only access the protected part of its own Base class. `b` could easily be part of a `class A : public Base` that C has no access to. – BoP Jan 02 '23 at 12:47
  • 3
    that will work `class C : public Base { void func(const C& c) { c.call(); } };` . Why? Because C++ standard says so. see: https://eel.is/c++draft/class.protected – PiotrNycz Jan 02 '23 at 13:00
  • Summary: `protected` is weird. There are good reasons for it, but it's still weird. – Pete Becker Jan 02 '23 at 14:08
  • @Someprogrammerdude -- re: "Why do you pass `b` as an argument?" -- because this is a **minimal reproducible example**. That's what people who ask questions are supposed to do. – Pete Becker Jan 02 '23 at 14:10
  • 1
    @molbdnilo -- this is a **minimal reproducible example**. That's what a good question should do. The question is "why doesn't this work?" and that's a perfectly reasonable question, especially given that this behavior is a bit of a quirk. – Pete Becker Jan 02 '23 at 16:32

0 Answers0