What is the reason for the following code that does not let me to create object.
class base
{
public:
void foo()
{ cout << "base::foo()"; }
};
class derived : private base
{
public:
void foo()
{ cout << "deived::foo()"; }
};
void main()
{
base *d = new derived();
d->foo();
}
It Gives me error :
” ‘type cast’ : conversion from
‘derived *’ to ‘base *’ exists, but is
inaccessible”
Thanks in advance 🙂
The problem is that you are using private inheritance; this means that inheritance can only be seen inside your class (in this case,
derived). You cannot point abase*to aderivedinstance outside your class (in this case, inmain()) because the inheritance (and hence, the conversion) cannot be accessed.This is exactly the same as trying to access a private member from outside a class.
In fact, the name “private inheritance” is quite misleading, since it does not implement real inheritance. In your example, a
derivedinstance is not abase; it is just implemented in terms of abase, and this is what “private inheritance” means. If you are tempted to use private inheritance, you should consider the possibility of using simple aggregation (i.e.: a private pointer tobaseinsidederived) instead. In most cases (most cases, not always), private inheritance offers no advantages and has some subtle problems.