teaching examples for inheritance and polymorphism

S

Stefan Ram

I was asked to teach »inheritance« and »polymorphism« in C++.

Usually, I would not approach teaching this way, but instead
teach »C++ class design« and then show what's appropriate,
possibly teaching delegation before inheritance. But now the
time is limited, so I cannot teach everything from ground up
in my way, and I still want to answer those questions as asked.

My problem is finding good teaching examples and exercises.
Somehow, I hate teaching inheritance by »a cow is an animal«
or »a rectangle is a square«, or polymorphism by
»cow.makeSound()« versus »cat.makeSound()«, because those
examples seem so artificially constructed for teaching but
rarely arise in real-world C++ applications.

Is anyone aware of examples where inheritance or
polymorphism really shines in C++, that are taken from
real-life applications of C++ or are something that can be
obviously useful in C++ programming, but are also rather
small and do not require too much knowledge of C++ (i.e.
only require knowledge of classes and derivation of classes
but not of, say, generics)? Some simple examples where
inheritance or polymorphism really makes sense?
 
R

Rui Maciel

Stefan said:
Is anyone aware of examples where inheritance or
polymorphism really shines in C++, that are taken from
real-life applications of C++ or are something that can be
obviously useful in C++ programming, but are also rather
small and do not require too much knowledge of C++ (i.e.
only require knowledge of classes and derivation of classes
but not of, say, generics)? Some simple examples where
inheritance or polymorphism really makes sense?

How about employing a strategy pattern to output a data structure to a file
according to a set of file formats?


Rui Maciel
 
A

Alain Ketterlin

I was asked to teach »inheritance« and »polymorphism« in C++. [...]
Is anyone aware of examples where inheritance or
polymorphism really shines in C++, that are taken from
real-life applications of C++ or are something that can be
obviously useful in C++ programming, but are also rather
small and do not require too much knowledge of C++ (i.e.
only require knowledge of classes and derivation of classes
but not of, say, generics)? Some simple examples where
inheritance or polymorphism really makes sense?

I like to use symbolic expressions, small ASTs that represent arithmetic
expressions: one purely virtual at the top, with sub-classes for
constants, variables, binary ops, etc. Typical operations are: printing,
evaluating (given a map from variables to values), and computing a
symbolic derivative. Then you can add classes for trigonometric
functions, add simplification, etc.

(A variant of this is representing boolean expressions, with operations
like computing normal forms, etc.)

-- Alain.
 
Ö

Öö Tiib

Is anyone aware of examples where inheritance or
polymorphism really shines in C++, that are taken from
real-life applications of C++ or are something that can be
obviously useful in C++ programming, but are also rather
small and do not require too much knowledge of C++ (i.e.
only require knowledge of classes and derivation of classes
but not of, say, generics)? Some simple examples where
inheritance or polymorphism really makes sense?

I would suggest to create some hierarchy of algorithmic art like
fractals or cellular automata. It is short code that produces
impressive visuals quickly so it is great to illustrate lecture.
The common interface is small (draw subset) but it is easy to show
how you can make different external functionality with it
(scrolling, zooming). It may make students to want to try
something like that own their own and such desire is from what
we all once started.
 
J

James Kanze

On Wednesday, 13 March 2013 08:15:12 UTC, Juha Nieminen wrote:

[...]
I have always said that object-oriented programming often feels like it
was invented to solve the problem of programming graphical user
interfaces. Unsurprisingly, the vast majority of GUI libraries use
class hierarchies extensively.

A GUI is an obvious example: the routine handling screen update
doesn't want to have to know the details of what it's redrawing.

Interestingly enough, the other two examples which come to mind
both predate OO by some decades, and are still often implemented
using ad hoc methods instead of inheritance. But when you call
write (the OS system level function), the behavior is clearly
different if the output is going to a file or to a window on the
screen: if you were writing a new OS from scratch today, it
would be plain silly to use anything but C++. And typically, in
parsing, tokens returned by the scanner will have different
semantics according to the token type: here too, an inheritance
hierarchy would seem in order.
 
S

Stefan Ram

Juha Nieminen said:
But that's a perfect example of bad inheritance.

I wanted to write »a square is a rectangle«
(this holds for values in the sense of:
Every pair of two same numbers (width,height)=
(x,x), is also a pair of two numbers (x,y).)
 
G

gianfranco.zuliani

Is anyone aware of examples where inheritance or

polymorphism really shines in C++, that are taken from

real-life applications of C++ or are something that can be

obviously useful in C++ programming, but are also rather

small and do not require too much knowledge of C++ (i.e.

only require knowledge of classes and derivation of classes

but not of, say, generics)? Some simple examples where

inheritance or polymorphism really makes sense?

http://www.carlopescio.com/2012/03/life-without-controller-case-1.html
 
S

Stuart

I was asked to teach »inheritance« and »polymorphism« in C++.

Usually, I would not approach teaching this way, but instead
teach »C++ class design« and then show what's appropriate,
possibly teaching delegation before inheritance. But now the
time is limited, so I cannot teach everything from ground up
in my way, and I still want to answer those questions as asked.

My problem is finding good teaching examples and exercises.
Somehow, I hate teaching inheritance by »a cow is an animal«
or »a rectangle is a square«, or polymorphism by
»cow.makeSound()« versus »cat.makeSound()«, because those
examples seem so artificially constructed for teaching but
rarely arise in real-world C++ applications.

Yeah, I hate those examples, too. I often fail to grasp the idea behind
those examples (if there is one), and even if I do, I often lack the
enthusiasm to get it to work (it's like working for the waste-bin).
Is anyone aware of examples where inheritance or
polymorphism really shines in C++, that are taken from
real-life applications of C++ or are something that can be
obviously useful in C++ programming, but are also rather
small and do not require too much knowledge of C++ (i.e.
only require knowledge of classes and derivation of classes
but not of, say, generics)? Some simple examples where
inheritance or polymorphism really makes sense?

What about this: Create a program that let's the user enter a function
R->R in the source code. The user should be able to compute the function
at various places and compute the derivation of the function. The set of
function that should be supported should enclose polynomials, sine and
cosine. New functions must be creatable from existing functions through
sums, products and composition. The following code should compile and
yield proper values:

int main ()
{
// TODO: Choose useful function!
Function f = Sine (Const (3) * Id * Id); // = sin(3x^2)
std::cout << f->Derive () (0.3) << std::endl;
// = 6x * cos(3x^2) = 1,73479
return 0;
}

This task introduces both polymorphism and operator overloading in a
nice manner. The problem domain should be easily comprehensible for high
school students. Once an interface for Function is agreed upon,
individual groups can implement different functions, so the task may be
possible to do in 90 minutes (I haven't tried this in a real class, so
it may be the case that this takes much longer).

It will take a while until students will realize that there needs to be
not only the primitive Function classes like Sine, Cosine, and Id, but
also some kind of meta-function classes for Products, Sums, and
Composition. Once this has been accomplished, they will probably use the
following interface for Function objects:

class FunctionInterface
{
public:
virtual double operator () (double x) const = 0;
virtual FunctionInterface* Derive () const = 0;
};

For simplicity's sake they should ignore any problems with leaking
memory. Once they got that to work, they will realize the syntax of main
function of the task cannot be achieved with pointers alone, at least
not operator () (Function* innerFunction), so they will have to use some
wrapping class. I used a class that simply derives from
std::shared_ptr<FunctionInterface> and adds operator ().

Maybe this is a bit too complicated for a single session, but the task
could be split into one session that implements the object-oriented
part, and one session that deals with memory management, and one session
that adds the operator overloading part. In this case you would have to
change the task a bit and make it more and more complicated.

A real nice feature would be, if you provided some sort of visualisation
that can be used to plot their functions. However, I would not let this
be done by the students, since this draws their attention too much away
from the concepts of C++ to the concepts of some GUI library.

Regards,
Stuart
 
S

Seungbeom Kim

For simplicity's sake they should ignore any problems with leaking memory.

This feels like "For simplicity's sake they should ignore const-
correctness", except that const-correctness is "much easier" to fix
later because the compiler keeps nagging until it's really fixed.

I would teach using the standard smart pointers correctly and
avoiding any memory leak in the first place.
 
S

Stuart

This feels like "For simplicity's sake they should ignore const-
correctness", except that const-correctness is "much easier" to fix
later because the compiler keeps nagging until it's really fixed.

I would teach using the standard smart pointers correctly and
avoiding any memory leak in the first place.

Given enough time, I would like the students to come up with the
interface on their own. Since such a course is most probably a
beginners course, they will probably don't know much about memory
management and how this can be addressed under C++ with smart
pointers (if they know about smart pointers already, chances are
high that they know about inheritance as well).

I tend to adopt the Donald E. Knuth style of teaching: Let's get
something done and then find all the shortcomings in the solution. And
you are absolutely right, with this philosophy I should have omitted
const-correctness as well.

Regards,
Stuart
 
B

Balog Pal

Is anyone aware of examples where inheritance or
polymorphism really shines in C++, that are taken from
real-life applications of C++ or are something that can be
obviously useful in C++ programming, but are also rather
small and do not require too much knowledge of C++ (i.e.
only require knowledge of classes and derivation of classes
but not of, say, generics)? Some simple examples where
inheritance or polymorphism really makes sense?

GuiShape::Draw()? with leafs like point, line, circle, polygon, etc?
You can even make it into a deeper hierarchy separated by closed and
open shapes and draw filled or just frame.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,534
Members
45,007
Latest member
obedient dusk

Latest Threads

Top