[Cs3] on type covariance

Mikhail Nesterenko mikhail at cs.kent.edu
Fri Jul 17 13:23:18 EDT 2015


CS3 students,

This is regarding today's discussion on type covariance in the
Prototype Design Pattern. 

So, the concrete clone() does not _have to_ return the covariant type
(of the concrete class). However, if it does, then the clients may be
able to take advantage of the expanded user interface of the derived
class.

Consider the example we studied 

   http://vega.cs.kent.edu/~mikhail/classes/cs3/Examples/Prototype/prototypeFigures.cpp

Fhe abstract class Figure is implemented as a prototype and it
declares abstract virtual function clone():

	 virtual Figure* Figure::clone()=0;

The derived class Square overloads it with an implementation. The
implementation may return the base time or the covariant type:
    
         Figure* Square::clone(); // returns base class type
	 Square* Square::clone(); // returns covariant type

However, if the derived class enriches the interface by declaring a
function, for example a function that changes the fill of the square:

	 Square::changeFill(char);

Then, if clone() returns the base class pointer, the enriched
interface may not be used, since this function is a member of the
derived class:

	Square *sp = prototypeSquare.clone(); // compiles only if clone()
	sp -> changeFill('*');                // returns covariant type


thanks,
-- 
Mikhail


More information about the cs3 mailing list