Search code examples
c++oopprotected

How to avoid protected class members?


I have read in many discussions that having protected class members is bad and I see the reasons for that. But given the example below, what is the most elegant way to make const int age private and to solve the problem that arises from that?

#include <iostream>

class Animal
{
    public:
        Animal(const int age) : age(age) {}
        void print_age() const { std::cout << age << std::endl; }
    protected:
        const int age;
};

class Dog : public Animal
{
    public:
        Dog(const int age) : Animal(age) {}
        void bark() const
        {
            if (age >= 1)
                std::cout << "Woof!" << std::endl;
            else
                std::cout << "(...)" << std::endl;
        }
};

int main()
{
    Dog dog(1);
    dog.print_age();
    dog.bark();
    return 0;
}

Solution

  • If you're referring to reasons such as in Why is Clean Code suggesting avoiding protected variables?, you also need to keep in mind that those guidelines are intended for real-world scenarios, where often inheritance hierarchies aren't as clearcut as Animal and Dog. With enterprise-level applications, it's tempting for many developers to think in terms of inheritance as if it would bring more organization in the future, but in reality variables are thoughtlessly thrown into the base class, over time bloating the structure and eroding the organizational context of its members.

    In your simple case, using protected is fine.