dimanche 9 juillet 2023

Can't access protected members in derived class in Decorator pattern implementation

I'm trying to implement the decorator pattern, but my derived/decorator class can't access protected members of it's "decorated" member which is of the base class type. Here's what I mean

#include <iostream>

class A
{
protected:
    void func() { std::cout << "func ran\n"; }
};

class B : public A
{
public:
    void func2() { a->func(); }
    A* a;
};

int main()
{
    A a;
    B b;
    b.a = &a;
    b.func2();
}

This code produces an error saying "func" is protected within this context.

I could add B as a friend of A but I don't wanna have to change the existing code everytime I add something.

Is there an alternative way to do this?

Aucun commentaire:

Enregistrer un commentaire