Reputation: 43
Can somebody explain why below code does not compile on error:
Error 1 error C2243: 'type cast' : conversion from 'Der *' to 'Base *' exists, but is inaccessible d:\users\lzizva\documents\mta\c++\projects\temp1\17022014.cpp 50 1 temp1
Error 2 error C2243: 'type cast' : conversion from 'Der *' to 'Base *' exists, but is inaccessible d:\users\lzizva\documents\mta\c++\projects\temp1\17022014.cpp 51 1 temp1
3 IntelliSense: conversion to inaccessible base class "Base" is not allowed d:\users\lzizva\documents\mta\c++\projects\temp1\17022014.cpp 50 12 temp1
4 IntelliSense: conversion to inaccessible base class "Base" is not allowed d:\users\lzizva\documents\mta\c++\projects\temp1\17022014.cpp 51 14 temp1
I thought that when there is private inheritance the child gets all the properties and methods and set them as private and it only should affect the subclasses of the child. What am I missing here? What does actually the compiler do ?
Thanks in advance, Liron
#include <iostream>
using namespace std;
class Base
{
int n;
Base* next;
public:
Base(int n, Base* next = NULL) : n(n), next(next)
{}
virtual void print() const
{
cout << n << endl;
if (next != NULL)
{
next->print();
}
}
virtual ~Base()
{
cout << "Base" << endl;
}
};
class Der : private Base
{
int counter;
public:
Der(int n, Base* next = NULL) : Base(n, next), counter(n){}
void print() const
{
cout << counter << endl;
Base::print();
}
~Der()
{
cout << "Der" << endl;
}
};
void main()
{
Der one(1);
Der two(2, &one);
Der three(3, &two);
three.print();
}
Upvotes: 2
Views: 664
Reputation: 227370
Despite the tight coupling between base and derived types, private inheritance is a "has-a" relationship, rather than an "is-a". It really is suited for inheriting implementations, not interfaces, and, as you have discovered, it cannot be used for polymorphism since references or pointers to the base type cannot bind to instances of the derived one.
When you make this call
Der two(2, &one);
you are attempting to bind &one
, a Derived*
to a Base*
.
See the uses and abuses of inheritance GOTW for more on private inheritance.
Upvotes: 3
Reputation: 354979
The problem is in the construction of two
and three
: The Der
constructor takes a Base*
, but you are passing Der*
pointers.
Because Der
privately derives from Base
, the Der
-> Base
conversion is inaccessible in main()
, thus the errors.
Upvotes: 5