0

In the following code:

struct A{
protected:
    virtual void IAmProtected() = 0;
};

struct B: public A{
private:
    A * a;
protected:
    void IAmProtected() override;
    
public:
    
    void doSomething(){
        a->IAmProtected(); // ERROR: 'IAmProtected' is a protected member of 'A'
    }
};

I get 'IAmProtected' is a protected member of 'A' which I find to be strange since B is in fact an extension of A.

I want to know

  1. Why does this happen?
  2. How can I prevent this?
Mr. Developerdude
  • 9,118
  • 10
  • 57
  • 95
  • 1
    A [quirk](https://stackoverflow.com/questions/13723217/why-cant-i-access-a-protected-member-variable-of-a-base-class-passed-into-a-fun) of `protected` access is that an instance of a derived class only has access to _its own_ protected members, not members belonging to another instance of the class. – Nathan Pierson Mar 03 '23 at 20:45
  • The `a->IAmProtected();` line is ***not*** accessing the protected function from "inside the class". It is attempting to access that protected function externally, calling it through a pointer to a class object. You are also making an error by calling a pure virtual function. – Adrian Mole Mar 03 '23 at 20:45
  • I'm not sure what you really want to achieve, but you're using both inheritance and composition (well, sort of) in `B`. Why do you derive `B` from `A` and also have an `A*` member? – Adrian Mole Mar 03 '23 at 20:48
  • @AdrianMole: I want to extend an existing class in Qt6 that I have no control over (QSyntaxHighlighter) and I want to implement a "union" class that will let me run the protected highlightBlock(const QString &text) for a list of child instances. I guess this will forever remain a pipedream. – Mr. Developerdude Mar 03 '23 at 21:03
  • You can do that with just inheritance. In `B` make your override `public` and then, inside that override just call `A::IamProtected()`. – Adrian Mole Mar 03 '23 at 21:10
  • If you can state what you want to achieve clearly, and in the question itself, then somebody may give you an answer. – Adrian Mole Mar 03 '23 at 21:11
  • What type are those child instances? Do you have control over that? Could you derive your own class from `QSyntaxHighlighter` that would expose a public wrapper over `highlightBlock`, and use this class for those child instances? – Igor Tandetnik Mar 03 '23 at 21:12

0 Answers0