Question 0-2

Suppose we have the following sequence of declarations in C++.

class A { };
class B : public A { };
class C : public A { };
class D : public B, C { };
Note that the following would be legal in C++.
B *b = new D();
Why would C++ prohibit the following statement?
A *a = new D();

Solution

This statement asks the C++ compiler to make a refer to the A sub-object of a newly created D object. Each D object has two A sub-objects - one by virtue of extending the B class, another by virtue of extending the C class. Because it is ambiguous which sub-object to select, C++ says that the compiler should reject such a statement.

Back to Exam Review 0