I have a base class with several public methods and want to derive a child class which inherits only certain functions, so I derived the child class using private inheritance. Also I vave come across several times (including C++ primer plus) that private inheritance is almost exactly like containment. Now I have a problem where I want to use a function defined in Base to be available in the derived class.
The derived class doesn't have any private members in addition to those required by the base class. I'm not sure how to define public method "func" for derived class as shown in the code.
class Base
{
private:
double *p;
public:
Base(int m, int n);
void fun(const Base & obj1, const Base & obj2)
};
class Derived : private Base
{
public:
Derived(int n) : Base(1,n) {}
void fun(const Derived & obj1,const Base & obj2)
{
/* The function fun in derived class works almost exactly
like fun in Base class but I don't know how to call
Base.Fun(...). Also all the data needed to perform
operations in this function is a part of the private
member of the base class which the Derived member can't
access.
*/
}
}
If I were to use containment I could have just defined as follows:
class Derived
{
private:
Base P;
public:
void fun(const Derived & obj1,const Base & obj2)
{
Base :: P.func(obj1.P,obj2);
}
};
This make me wonder if containment is more appropriate here than private inheritance. On the other hand I'm not sure if either of the implementations are correct. So I'm looking for possible ways to do this.
Please note that I have not shown copy constructors,assignment and operators and some other methods in the codes above but I'm aware of their requirement. The codes are just to serve the basic purpose of showing private inheritance and containment.