Inheritance with Private Base Class Data Members

So I was told using protected for a base classes data members is bad software engineering practice due to small changes in this base class can break the derived classes implementation. So now I'm curious on how you would otherwise access the base classes private data members through the derived class, please use the following code as an example:

class automobile
{
public:
automobile(string color, int wheels);
...(assume appropriate setter and getter functions)
private:
string color;
int wheels;
};

how would a base class car for example be able to access/manipulate the color data member?
You are talking about the class itself and not a pointer to the derived class, yes?

You can make Car a friend class of automobile, then automobile can have access to cars members:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

//forward declaration

class car;

class automobile
{
public:

friend class car;
automobile(string color, int wheels);
...(assume appropriate setter and getter functions)
private:
string color;
int wheels;
};


In all honesty, if you have to do so, then your design is lacking and needs to be improved.
closed account (zb0S216C)
Sanel wrote:
"I was told using protected for a base classes data members is bad software engineering practice due to small changes in this base class can break the derived classes implementation."

If a derived class is broken when the base class from which it derives is modified, it's not because of protected members but from poor class design on your part. In fact, if protected members are used correctly, protected members can enhance encapsulation along with friends.

Sanel wrote:
"...(assume appropriate setter and getter functions)"

No. If you're going to provide the means to get and set private and/or protected members, you may as well declare those members public. You should be aware that level of access in classes is there for a reason and get/setting every member is just counter-encapsulation.

Wazzak
Topic archived. No new replies allowed.