Wednesday 24 April 2013

Object Oriented Programming

Rationale
C++ started life as “C with classes”. A class contains the data and the operations needed
on the data, and so the class defines the interface to the data. Classes permit the definition
of abstract data types (ADTs) in a similar way to the packages of ADA and the modules
of Modula-2. If the interface to the object is well designed then all the details will be within
the class, making it easier to identify code that is accessing the data incorrectly. This is part
of way to an object oriented programming language (OOPL).
For a programming language to fully support OOP it should also support inheritance and
polymorphism.
inheritance defining a class in terms of another; adding features to the existing
class
polymorphism applying the same operation to objects of different classes (but each
must be in the same family, derived from a common base class), the
behaviour will be different, even though the operation is the same
The classic example of inheritance and polymorphism is that of shapes in a graphics library.
Abase class, shape, stores the colour and location, and new classes are derived from the
base class inheriting the common features of all shapes. If any shape is asked to draw itself,
the behaviour will be different (circles and squares look different) even though they are
undergoing the same operation; this is polymorphism.
Much work is being done in the fields of object oriented analysis (OOA) and object
oriented design (OOD), but unfortunately this is beyond the scope of this course (and
possibly beyond the capabilities of the author!). However, the following rules of thumb for
object oriented programming in C++ from Stroustrup [1] will suffice:
– If you can think of “it” as a separate idea, make it a class .
– If you can think of “it” as a separate entity, make it an object of some class .
– If two classes have something significant in common, make that commonality a base
class.
– If a class is a container of objects, make it a template .
Deriving a class from another (inheritance) and including a class object within another are
often referred to as is-a and has-a relationships. In C++:
is-a publicly derived from another class
has-a implemented in terms of; either has a class object as a member or is privately
derived from another class
For example, a Ford Mondeo is-a car, and a car has-a engine (sorry about the grammar!).
Therefore, engine could be a member of car, and FordMondeo could be publicly derived
from car.

No comments:

Post a Comment