Interview Question
The problem occurs at the upcasting part. If we run
der *b = new der;
, then the constructor of the base class can still be called. It means we have no problem to run "new der".
However, when we try upcast a pointer of der type to one of base type, something is wrong, even though I don't exactly know what is wrong. Who can explain a little bit.
<pre lang="c++" line="1" title="CodeMonkey88943" class="run-this">// There would be problems with interface (public methods)
- Anonymous December 03, 2010// Suppose, we have following classes:
class Base {
int _a;
public:
Base(int aa = 0) : _a(aa) {}
int geta() { return _a; }
};
class Derived : Base {
public:
Derived(int aa = 0) : Base(aa) {}
};
void SomeFunc(Base* ob) {
// so here, if ob is Derived and if we have private inheritance, how
// geta() would be called? In derived it has become "private".
// I.e. interface has become inaccessable
cout << ob->geta() << endl;
}
int main()
{
Base* d = new Derived(44); // that`s why compiler finds an error here
Base* b = new Base(55);
SomeFunc(d);
SomeFunc(b);
return 0;
}
</pre><pre title="CodeMonkey88943" input="yes">
</pre>