0% found this document useful (0 votes)
7 views

Chapter 6 Class Relationships

Chapter 6 discusses class relationships, focusing on inheritance, which allows subclasses to inherit features from superclasses, promoting code reuse and organization. It outlines different types of inheritance, including single and multiple inheritance, and explains access specifiers like public, private, and protected. The chapter also covers concepts like composition and aggregation, illustrating how objects can be related and interact within a program.

Uploaded by

linzskybes
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

Chapter 6 Class Relationships

Chapter 6 discusses class relationships, focusing on inheritance, which allows subclasses to inherit features from superclasses, promoting code reuse and organization. It outlines different types of inheritance, including single and multiple inheritance, and explains access specifiers like public, private, and protected. The chapter also covers concepts like composition and aggregation, illustrating how objects can be related and interact within a program.

Uploaded by

linzskybes
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 61

Chapter 6

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

• subclass, derived class, child class:


terms to describe the child in the
relationship, which accepts functionality
from its parent

• extend, inherit, derive: become a subclass


5
of another class
Inheritance Examples
Base Class Derived Classes
Student CommuterStudent
ResidentStudent
Shape Circle
Triangle
Rectangle
Loan CarLoan
HomeImprovementLoan
MortgageLoan
6
Inheritance Examples
Base Class Derived Classes
Employee Manager
Researcher
Worker
Account CheckingAccount
SavingAccount

7
Inheritance Examples
• Inheritance synonyms
– is-a
– is-a-kind-of
– is-like-a
– gen-spec

8
Inheritance Hierarchy – Example 1
Superclass
Vehicle
Subclasses

Automobile Motorcycle Bus

Sedan Sports Car Luxury Bus School Bus

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.

FlyingThing Multiple Inheritance Animal

Airplane Helicopter Bird Wolf Horse

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

(a) Single Inheritance (b) Multiple Inheritance (c) Hierarchical Inheritance


A A
A

B c B c
B

C D D

(a) Multi-Level Inheritance (b) Hybrid Inheritance (c) Multipath Inheritance


17
Implementing Inheritance
• Base class/Super class
– Defines all qualities common to any derived
classes.

• 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.

• However, all private elements of base will


remain private to it and are not directly
accessible by derived.

22
Example: main()
int main() {
derived ob;
ob.setx(10);
ob.sety(20);
ob.showx();
ob.showy();
}

23
An incorrect example

class derived : public base {


int y;
public:
void sety(int n) { y = n; }
/* Error ! Cannot access x, which is
private member of base. */
void show_sum() {cout << x+y; }
};
24
Access Specifier: private
• If the access specifier is private:
– public members of base become private
members of derived.
– these members are still accessible by
member functions of derived.

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

class derived : private base {


int y;
public:
// setx is accessible from within derived
void setxy(int n, int m) { setx(n); y = m; }
// showx is also accessible
void showxy() { showx(); cout<<y<< ‘\n’;}
};

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

• Type 1: inherit as private


Base Derived

private members inaccessible

protected members private members

public members private members

30
Summary of Access Specifiers
• Type 2: inherit as protected

Base Derived

private members inaccessible

protected members protected members

public members protected members

31
Summary of Access Specifiers
• Type 3: inherit as public

Base Derived

private members inaccessible

protected members protected members

public members public members

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

We will now declare a DeriDemo object.


This is the BaseDemo constructor.
This is the DeriDemo constructor.
The program is now going to end.
This is the DeriDemo destructor.
This is the BaseDemo destructor.

37
Passing arguments
• What if the constructor functions of both the
base class and derived class take
arguments?

1. Pass all necessary arguments to the derived


class’s constructor.

2. Then pass the appropriate arguments along to


the base class.
38
Passing arguments (cont’d)
• Assume a class called Cube is derived from a class
called Rect.
• Rect constructor
Rect::Rect(float w, float l)
{
width = w;
length = l;
area = length * width;
}

• 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)

• Note that the derived class constructor must


take enough arguments to be able to pass to
the base class constructor

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"

// Definition of Rect constructor.


Rect::Rect(float w, float l)
{
width = w;
length = l;
area = width * length;
}

42
Program continues
Contents of cube.h

#ifndef CUBE_H
#define CUBE_H
#include "rect.h"

// Cube class declaration


class Cube : public Rect
{
protected:
float height;
float volume;
public:
Cube(float, float, float);
float getHeight(void) { return height; }
float getVol(void) { return volume; }
};
#endif 43
Program continues
Contents of cube.cpp

#include "cube.h"

// Definition of Cube constructor.


Cube::Cube(float wide, float long, float high) :
Rect(wide, long)
{
height = high;
volume = area * high;
}

44
Program continues

Contents of the main program, programTest.cpp


// This program demonstrates passing arguments to a base
// class constructor.

#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;

Cube holder(cubeWide, cubeLong, cubeHigh);


cout << "Here are the Cube's properties:\n";
cout << “Width: " << holder.getWidth() << endl;
cout << “Length: " << holder.getLen() << endl;
cout << “Height: " << holder.getHeight() << endl;
cout << “Base area: " << holder.getArea() << endl;
cout << “Volume: " << holder.getVol() << endl;
} 45
Program Output with Example Input

Enter the dimensions of a Cube:


Width: 10 [Enter]
Length: 15 [Enter]
Height: 12 [Enter]

Here are the Cube's properties:


Width: 10
Length: 15
Height: 12
Base area: 150
Volume: 1800

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

▪ Must be first action in the child constructor


47
Summary on Inheritance
• What is Inherited
– Data members
– Most member functions
• Functions not inherited
– Constructors
– Destructors
– Friend functions
– Assignment (=) operator
• All constructors and destructors in the hierarchy are
executed
– Constructors from the least to the most derived (general to
specific classes)
– Destructors from the most to the least derived (specific to
general classes) 48
Composition

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

You might also like