Tuesday, March 6, 2012

C++ and Subtyping Fun

Question: In the following C++11 program, what lines will fail to compile?

Answers are colored white below if you want to give a try before highlighting it.

Answer: 14, 16, 25, 26, 28, 31, 32.

The keyword is subtyping.

Here's the explanation:

If you declare a function to receive type A and return type A (function f1 in the example), you're promising that it can receive type A or it's subclasses, and return A or it's subclasses. The caller will expect to be able to do all of the following:

a = f1(a);
a = f1(subclass_of_a);
superclass_of_a = f1(a);
superclass_of_a = f1(subclass_of_a);

So anything assigned to f1 must be able to do all of the following. Take ab in line 14 for example, it can only accept B and its subclasses as a parameter. What if somebody passed in an A?

How about, line 31? The caller of f4 is expecting B or its subclass as a return value. What if the function returned A? That's why line 31 is invalid.



  1. Cool quiz! Reminds me of grad school days.

  2. Unfortunately, although not unexpected XD, I failed to answer correctly.