lundi 27 mai 2019

What's wrong with protected members and what's the alternative?

I've been recently told that protected members are bad and after doing some reading it seems that it is indeed the consensus. So what should I do instead?

Let's say I'm working on a set of Widget classes and each and every widget is supposed to have a number of common attributes (e.g. foo, bar and baz). I could define the base class as follows:

class Widget
{
public:
    virtual ~Widget() = default()

    Foo foo() const;
    Bar bar() const;
    Baz baz() const;

    virtual void someInterfaceMethod() = 0;

protected:
    Foo m_foo;
    Bar m_bar;
    Baz m_baz;
};

Widget::foo() { return m_foo; } // etc.

What's so bad about it and what is a better way to implement it? Should I make Widget an inteface only class and then define those members in each and every derived widget? Should I make them private and use get() & set() methods in the constructor of derived class instead? Should I make them private and change Widget constructor to take them as arguments? What if they can't be fully initialized until after construction.

Aucun commentaire:

Enregistrer un commentaire