Can we inherit private members of a Base class into public members of a Derived class?

Viewed 176

The problem is I need Base-class's Private members into Derived-class Public members but there I can find only two main types of keywords to Inherit private which is the default type and public which Inherit all things as same as they are in Base-class. But I need to inherit only Private members of the Base-class into public members of the Derived-class. Can someone help me out with this!

1 Answers

You wants a class Base has publicData and privateData, but only privateData is inherited in derived class.

This is might be an XY problem. I presume you want two classes to have "some data" in common, but achieving it by inheritance in inappropriate is this case.

Partially inheritance break the concept of inheritance, and I suggest to use composition.

Most of time composition and aggregation are the better solution.

Here's a composition example for using the same private data without inheritance.

If you really need to inherit private data, make them protected in Base and no public data. Or multiple inheritances which I suggest only use interface style won't bite you less in the future.

If this cannot answer your question, please update your question for detailed use case. Eg: you need to refactor something or some limitation.


struct Data{
int val;
};

class Base{
public:
void SomeFunction();

protected:
Data m_Data;
};


class Derived: public Base{
// You will have protected m_Data here.
};

class AnotherClass{ // A class has data in common
private:
Data m_Data;
};

Related