tags:

views:

119

answers:

3

I have a question which kind of applies to all languages with static typing and some sort of OOP.

If I have a class A, a class B which is a child of A, and a class C which is a child of B and a variable of the type A, can I store instances of B and C in it also?

+4  A: 

In C++ the answer is no. If the type were A* or A&, the answer would be yes, but for just A it's no.

In Java, C# and other languages where variables are references to objects by default, the answer is yes.

sepp2k
What about Delphi?
Alma
In Delphi the answer is also yes.
sepp2k
or `void *` [[[[now I have to fill comment with at least 15 characters]]]]
doc
+6  A: 

In Delphi, the answer is yes.

For instance, I have created a syntax-highlighting text editor component. This component has a property FormattingProcessor, which is of type TFormattingProcessor. Now, I have created several formatting processors, e.g. TXMLFormattingProcessor, TPascalFormattingProcessor, and TINIFormattingProcessor, each class being a child of TFormattingProcessor. Any of these can be assigned to the FormattingProcessor property of the text editor component.

That is, the variable declared as TFormattingProcessor can be assinged a value of type TXMLFormattingProcessor, TPascalFormattingProcessor, or TINIFormattingProcessor, for instance.

If you look around in the VCL, you see that this type of assignments are actually very common. For instance, the TLabel component has a FocusControl property, which is of type TWinControl (if I recall correctly). You can assign any decendant of TWinControl to this property, e.g. a TEdit. (The FocusControl is the control that will obtain keyboard focus when the accelerator character of the label is typed together with the Alt key.)

Andreas Rejbrand
Nice explanation.
Ulrich Gerhardt
+1  A: 

This question cannot be answered reliably without knowing what type of inheritance is meant when you say a class 'B' is a child of 'A' and where the access is being done. In other words, without knowing if the base is accessible and unambiguous, it is not possible to answer this question correctly.

$11.2/4 - "A base class is said to be accessible if an invented public member of the base class is accessible."

Assuming that 'A' is an unambiguous and accessible base of 'B', and 'B' is an unambiguous and accessibe base of 'C', and 'A', 'B' and 'C' are concrete classes (no pure virtual function)

B b;
C c;

A &rb = b;       // OK
A &rc = c;       // OK 

A *pb = &b;      // OK
A *pc = &c;      // OK

A a1 = b;        // sliced, only 'A' subobject of 'B' is copied onto 'a1', may be a logical error
A a2 = c;        // sliced, only 'A' subobject of 'C' is copied onto 'a2', may be a logical error
Chubsdad