Chapter 6 Class Relationships
Chapter 6 Class Relationships
Class Relationships
Introduction
• Are depicted as diagrams
• PAre represented as connected graphs
– Nodes or vertices are classes (rectangles)
– Edges, arcs, or paths denote the relationship
(connecting lines)
• Allow objects to cooperate in the solution of a
problem
– Objects communicate by sending messages along
the connections
– Objects can call functions in connected objects
• Are supported by specific computer-language
syntax
2
Inheritance
3
Inheritance
• Relationship between a class and a more refined
version
• Abstraction for sharing similarities among classes
while preserving their differences
– Mechanism for code reuse
– Conceptual simplification by reducing the number of unique
features
• Each subclass inherits all features of the superclass
• An instance of a subclass is simultaneously an
instance of all its ancestor classes (i.e., it contains
subclasses)
• Overriding— subclass defines operation with the
4
same name and signature
Inheritance terms
• superclass, base class, parent class:
terms to describe the parent in the
relationship, which shares its functionality
7
Inheritance Examples
• Inheritance synonyms
– is-a
– is-a-kind-of
– is-like-a
– gen-spec
8
Inheritance Hierarchy – Example 1
Superclass
Vehicle
Subclasses
What properties does each vehicle inherit from the types of vehicles
above it in the diagram?
Inheritance Hierarchy – Example 2
10
Inheritance Types
• Single Inheritance: if a new class is a
subclass of a single parent class.
– Relationships among classes in this type of
inheritance can be shown in a derivation
tree.
• Multiple Inheritance: if a new class has
more thn one parent class.
– Relationships among classes in this type of
inheritance can be shown in a derivation
graph. 11
Single Inheritance – Example 1
Person
Name
Birthday
Student Employee
Student ID Employee
ID
12
Example 1: Single Inheritance
(cont’d)
• In the above example, a Student is a type of
Person.
• Likewise, a Employee is a type of Person.
• Both Student and Employee inherit all the
attributes and methods of Person.
• Student has a locally defined student ID
attribute.
• Employee has a locally defined employee ID
attribute.
• If you look at a Student object, you see
attributes of name, date of birth and student ID. 13
Single Inheritance – Example 2
• One class inherits from another.
Ancestor
Account
- balance
Superclass - name
- number
(parent)
+ withdraw()
+ createStatement()
Inheritance
Relationship
Savings Checking
Subclasses
Descendents 14
Multiple Inheritance Example
• A class can inherit from several other
classes.
Use multiple inheritance only when needed and always with caution!
15
Multiple Inheritance Example
•Bird inherits from both FlyingThing and Animal.
•Multiple inheritance is conceptually straight forward and may
be needed to model the real world accurately.
•However, there are potential implementation problems when
you use multiple inheritance, and not all implementation
languages support it.
•Use multiple inheritance only where it accurately describes the
concept you are trying to model and reduces the complexity of
your model.
•Be aware, however, that this representation will probably need
to be adjusted in design and implementation.
•Generally, a class inherits from only one class. 16
Inheritance Types Summary
A A B A
B C B C D
B c B c
B
C D D
• Derived class/Subclass
– Inherits those general properties and adds
new properties that are specific to that class.
18
Example: Base Class
class base {
int x;
public:
void setx(int n) { x = n; }
void showx() { cout << x << ‘\n’ }
};
19
Example: Derived Class
// Inherit as public
class derived : public base {
int y;
public:
void sety(int n) { y = n; }
void showy() { cout << y << ‘\n’;}
};
20
Inheritance Example
• This example determines which method is called
21
Access Specifier: public
• The keyword public tells the compiler that
base will be inherited such that:
– all public members of the base class will
also be public members of derived.
22
Example: main()
int main() {
derived ob;
ob.setx(10);
ob.sety(20);
ob.showx();
ob.showy();
}
23
An incorrect example
25
Example: Derived Class
// Inherit as private
class derived : private base {
int y;
public:
void sety(int n) { y = n; }
void showy() { cout << y << ‘\n’;}
};
int main() {
derived ob;
ob.setx(10); // Error! setx() is private.
ob.sety(20); // OK!
ob.showx(); // Error! showx() is private.
ob.showy(); // OK!
26
}
Example: Derived Class
27
Protected Members
• Sometimes you want to do the following:
– keep a member of a base class
private
– allow a derived class access to it
• Use protected members!
• If no derived class, protected members is
the same as private members.
28
Protected Members
The full general form of a class
declaration:
class class-name {
// private members
protected:
// protected members
public:
// public members
}; 29
Summary of Access Specifiers
30
Summary of Access Specifiers
• Type 2: inherit as protected
Base Derived
31
Summary of Access Specifiers
• Type 3: inherit as public
Base Derived
32
Summary on Inheritance
• Derived class inherits from base class
• Public Inheritance (“is a”)
– Public part of base class remains public
– Protected part of base class remains protected
• Protected Inheritance (“contains a”)
– Public part of base class becomes protected
– Protected part of base class remains protected
• Private Inheritance (“contains a”)
– Public part of base class becomes private
– Protected part of base class becomes private
33
Constructor and Destructor
• It is possible for both the base class and
the derived class to have constructor
and/or destructor functions.
• The constructor functions are executed
in order of derivation.
– i.e. the base class constructor is executed
first.
• The destructor functions are executed in
reverse order.
34
Example: Destructors and Constructors
// This program demonstrates the order in which base and
// derived class constructors and destructors are called.
// For the sake of simplicity, all the class declarations
// are in this file.
#include <iostream.h>
// BaseDemo class
class BaseDemo
{
public:
BaseDemo(void) // Constructor
{ cout << "This is the BaseDemo constructor.\n";
}
~BaseDemo(void) // Destructor
{ cout << "This is the BaseDemo destructor.\n";
}
};
35
Program continues
class DeriDemo : public BaseDemo
{
public:
DeriDemo(void) //Constructor
{ cout << "This is the DeriDemo
constructor.\n"; }
~DeriDemo(void) // Destructor
{ cout << "This is the DeriDemo
destructor.\n"; }
};
void main(void)
{
cout << "We will now declare a DeriDemo object.\n";
DeriDemo object;
cout << "The program is now going to end.\n";
}
36
Program Output
37
Passing arguments
• What if the constructor functions of both the
base class and derived class take
arguments?
• Cube Constructor
Cube::Cube(float wide, float long, float high) :
Rect(wide, long)
{
height = high;
volume = area * high;
}
39
General Form:
<class name>::<class name>(parameter list) : <base
class name> (parameter list)
40
Example
Contents of rect.h
#ifndef RECT_H
#define RECT_H
// Rect class declaration
class Rect
{
protected:
float width;
float length;
float area;
public:
Rect(void) { width = length = area = 0.0; }
Rect(float, float);
float getArea(void) { return area; }
float getLen(void) { return length; }
float getWidth(void) { return width; }
};
#endif
41
Program continues
Contents of rect.cpp
#include "rect.h"
42
Program continues
Contents of cube.h
#ifndef CUBE_H
#define CUBE_H
#include "rect.h"
#include "cube.h"
44
Program continues
#include <iostream.h>
#include "cube.h"
void main(void)
{
float cubeWide, cubeLong, cubeHigh;
cout << "Enter the dimensions of a Cube:\n";
cout << “Width: "; cin >> cubeWide;
cout << “Length: "; cin >> cubeLong;
cout << “Height: "; cin >> cubeHigh;
46
Constructors in Derived Classes
• A derived class does NOT inherit the
constructors from the base class
▪ Constructor in a derived class must invoke
constructor from base class
• Use the reserved word super
49
Composition
• Containment or “contains a” also “has
a”
• Form of association
– strong ownership / binding
• parts belong to one whole
• parts & whole have coincident
lifetimes
• instantiate parts in whole constructor
• parts do not change during execution
– implemented with object attributes
50
Composition Example
• Making complex from simple
51
Composition Example
52
Aggregation
53
Aggregation
• Whole-part, “has-a,” assembly, or “a
part-of”
• Form of association
– weak ownership / binding
• parts & whole have independent
lifetimes
• instantiate parts when convenient
• build relationship when convenient
• parts may belong to multiple wholes
• parts may change during execution
– implemented with object pointer
attributes
54
Associations
55
Associations
• A subordinate relationship
• Associations are connections between peer objects,
which allows objects to call each others functions
• Implemented as object references (i.e., class-scope
variables that reference to other objects)
• Associated objects may not be permanent nor must
they be created at the same time (i.e., they have
separate existences)
• Associations are bidirectional; the association name
indicates a forward direction and an inverse direction
– are sometimes shown with a single, non-directional line
– are sometimes shown as one or two directed lines (arrows)
56
Association Example
57
Dependency
58
Dependency
• One object uses another
• A relationship where one object requires a feature
(attribute or operation) from another object
• Is implemented through local-scope object reference
variables
– instantiating a local object
– passing an object as a parameter to a function
• Is not implemented by extracting the needed feature
– “Passing the entire gorilla, just to get at its liver, is messy,
cumbersome, and annoys the hell out of the gorilla”
– Nonetheless, “passing the entire gorilla” preserves the used
object’s integrity and maintains the spirit of the object model
• Ephemeral form of association
59
• Also known as delegation or using
Dependency Example
60
Overriding Inherited Functions
61