0% found this document useful (0 votes)
20 views59 pages

Oom in Uml

The document outlines a course on Object Oriented Modeling using Unified Modeling Language (UML), taught by Mr. Smith Wills. It covers various modules including basic techniques of modeling, prominent object-oriented methodologies, and an introduction to UML, detailing different types of UML diagrams and their applications. Key concepts such as association, aggregation, composition, generalization, and dependency in object-oriented design are also discussed.

Uploaded by

barachelmboumo
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)
20 views59 pages

Oom in Uml

The document outlines a course on Object Oriented Modeling using Unified Modeling Language (UML), taught by Mr. Smith Wills. It covers various modules including basic techniques of modeling, prominent object-oriented methodologies, and an introduction to UML, detailing different types of UML diagrams and their applications. Key concepts such as association, aggregation, composition, generalization, and dependency in object-oriented design are also discussed.

Uploaded by

barachelmboumo
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/ 59

COURSE INSTRUCTOR Mr.

SMITH WILLS

OBJECT ORIENTED MODELLING IN


UNIFIED MODELLING LANGUAGE
COURSE INSTRUCTOR Mr. SMITH WILLS

TABLE OF CONTENTS
MODULE 01 .......................................................................................................................................... 1
INTRODUCTION TO OBJECT ORIENTED MODELING ........................................................... 1
1. BASIC TECHNIQUES OF MODELING COMPUTER SYSTEMS ....................................... 1
2. OVERVIEW OF PROMINENT OBJECT-ORIENTED METHODOLOGIES ..................... 1
2.1. ASSOCIATION ......................................................................................................................... 1
2.1.1. AGGREGATION .................................................................................................................. 2
2.1.2. COMPOSITION.................................................................................................................... 3
2.2. GENERALIZATION ................................................................................................................ 5
2.3. DEPENDENCY ......................................................................................................................... 7
MODULE 02 .......................................................................................................................................... 8
INTRODUCTION TO UML (UNIFIED MODELING LANGUAGE) ............................................ 8
1. INTRODUCTION ......................................................................................................................... 8
1.1. GOALS OF UML ...................................................................................................................... 8
1.2. ROLE OF UML IN OBJECT ORIENTED DESIGN ............................................................ 8
1.3. UML MODELLING TYPES ................................................................................................... 9
1.4. UML DIAGRAMS OVERVIEW ............................................................................................. 9
I. CLASS DIAGRAM ..................................................................................................................... 10
II. COMPONENT DIAGRAM.................................................................................................... 12
III. DEPLOYMENT DIAGRAM ................................................................................................. 13
IV. OBJECT DIAGRAM .............................................................................................................. 13
V. PACKAGE DIAGRAM .............................................................................................................. 14
VI. USE CASE DIAGRAM........................................................................................................... 15
VII. ACTIVITY DIAGRAM .......................................................................................................... 15
VIII. STATE MACHINE DIAGRAM ........................................................................................ 17
IX. SEQUENCE DIAGRAM ........................................................................................................ 18
MODULE 03 ........................................................................................................................................ 23
INTRODUCTION TO OBJECTED-ORIENTED DESIGN ........................................................... 23
1. INTRODUCTION ....................................................................................................................... 23
I. C++ CLASSES/OBJECTS ......................................................................................................... 23
II. INHERITANCE ...................................................................................................................... 25
III. POLYMORPHISM ................................................................................................................. 30
A. COMPILE TIME POLYMORPHISM ..................................................................................... 32
i. FUNCTION OVERLOADING .................................................................................................. 32
ii. OPERATOR OVERLOADING ................................................................................................. 33
B. RUNTIME POLYMORPHISM ................................................................................................. 34
COURSE INSTRUCTOR Mr. SMITH WILLS

iii. FUNCTION OVERRIDING .................................................................................................. 34


iv. VIRTUAL FUNCTION .......................................................................................................... 34
IV. ENCAPSULATION ................................................................................................................ 36
V. ABSTRACTION .......................................................................................................................... 41
VI. INTERFACES ......................................................................................................................... 43
VII. CONSTRUCTORS .................................................................................................................. 46
VIII. EXCEPTION ....................................................................................................................... 53
COURSE INSTRUCTOR Mr. SMITH WILLS
MODULE 01
INTRODUCTION TO OBJECT ORIENTED MODELING

1. BASIC TECHNIQUES OF MODELING COMPUTER SYSTEMS


System modelling is a crucial aspect of software engineering, providing a visual
representation of a system's structure, behaviour, and interactions. Various techniques are
employed to effectively model computer systems. Some commonly used ones include;
 UML
 DFD’s
 ER-Diagrams
The appropriate modelling technique depends on the specific goals and complexity of the
system being modelled. For example, UML is well-suited for object-oriented systems, while
DFDs can be effective for data-centric systems.
By effectively combining these techniques, system analysts and developers can create clear,
concise, and comprehensive models that aid in understanding, designing, and implementing
complex computer systems.

2. OVERVIEW OF PROMINENT OBJECT-ORIENTED METHODOLOGIES


Object-Oriented Programming (OOP) has revolutionized software development by providing a
structured approach to modelling real-world entities as objects. To guide this process, various
methodologies have emerged. Thus, an Object-oriented methodology is a way of viewing
software components and their relationships. Object-oriented methodology relies on three
concepts that define object-oriented languages: encapsulation, polymorphism, and
inheritance.
In UML diagrams, relationships are used to link several things. It is a connection between
structural, behavioural, or grouping things. Following are the standard UML relationships
enlisted below:
 Association
 Dependency
 Generalization

2.1.ASSOCIATION
Association relationship is a structural relationship in which different objects are linked
within the system. It exhibits a binary relationship between the objects representing an activity.
It depicts the relationship between objects, such as a teacher, can be associated with multiple
students.
It is represented by a line between the classes followed by an arrow that navigates the
direction, and when the arrow is on both sides, it is then called a bidirectional association. We
can specify the multiplicity of an association by adding the adornments on the line that will
denote the association.

1
COURSE INSTRUCTOR Mr. SMITH WILLS

Example:

Key Characteristics of Association:


 Bidirectional or Unidirectional: Associations can be bidirectional, where both classes
are aware of each other, or unidirectional, where only one class knows about the other.
 Multiplicity: This defines how many instances of one class can be associated with
instances of another class. For example, one-to-one, one-to-many, or many-to-many
relationships.
 Role Names: These are labels that describe the role played by the instances in the
association. For example, in an association between a Teacher and Student, the role
names could be teaches and learns.
 Navigability: This indicates whether an instance of one class can navigate to an instance
of another class. It is often represented by an arrow on the association line.
Exercise 1
Consider a simple association between a Customer and an Order:
 A Customer can place multiple Orders.
 An Order is placed by exactly one Customer.
The composition and aggregation are two subsets of association. In both of the cases, the object
of one class is owned by the object of another class; the only difference is that in composition,
the child does not exist independently of its parent, whereas in aggregation, the child is not
dependent on its parent i.e., standalone. An aggregation is a special form of association, and
composition is the special form of aggregation. This can be seen below

2.1.1. AGGREGATION
Aggregation is a subset of association; it is a collection of different things. It is more specific
than an association. It describes a whole-part or part-of the relationship. It is a binary
association, i.e., it only involves two classes. It is a kind of relationship in which the child is
independent of its parent.

2
COURSE INSTRUCTOR Mr. SMITH WILLS

Example:

These parts can exist independently of the larger class and may be shared among multiple
wholes. With our football example, a team will aggregate players, but players can still exist on
other teams or as free agents. The shape of this connection is a hollow diamond attached to the
"part" with a solid line going back to the "whole" or class.
Exercise 2:
Consider a Department and Employee relationship:
 A Department can have multiple Employees.
 An Employee can exist independently of the Department.

2.1.2. COMPOSITION
The composition is a part of aggregation, and it portrays the whole-part relationship. It depicts
dependency between a composite (parent) and its parts (children), which means that if the
composite is discarded, so will its parts get deleted. It exists between similar objects.
As you can see from the example given below, the composition association relationship
connects the Person class with Brain class, Heart class, and Legs class. If the person is
destroyed, the brain, heart, and legs will also get discarded.
Here we are considering a car and a wheel example. A car cannot move without a wheel. But
the wheel can be independently used with the bike, scooter, cycle, or any other vehicle. The
wheel object can exist without the car object, which proves to be an aggregation relationship.

3
COURSE INSTRUCTOR Mr. SMITH WILLS

Example

Exercise 3:
Consider a House and Room relationship:
 A House (whole) consists of multiple Rooms (parts).
 If the House is demolished, all Rooms are also destroyed.

4
COURSE INSTRUCTOR Mr. SMITH WILLS

ASSOCIATION AGGREGATION COMPOSITION

Association relationship is Aggregation relationship is The composition


represented using an represented by a straight line relationship is represented
arrow. with an empty diamond at by a straight line with a
one end. black diamond at one end.

In UML, it can exist It is a part of the association It is a part of the aggregation


between two or more relationship. relationship.
classes.
It incorporates one-to-one, It exhibits a kind of weak It exhibits a strong type of
one-to-many, many-to-one, relationship. relationship.
and many-to-many
association between the
classes.
It can associate one more In an aggregation In a composition
object together. relationship, the associated relationship, the associated
objects exist independently objects cannot exist
within the scope of the independently within the
system. scope of the system.
In this, objects are linked In this, the linked objects are Here the linked objects are
together. independent of each other. dependent on each other.
It may or may not affect Deleting one element in the It affects the other element if
the other associated aggregation relationship one of its associated
element if one element is does not affect other elements is deleted.
deleted. associated elements.
Example: A tutor can Example: A car needs a Example: If a file is placed
associate with multiple wheel for its proper in a folder and that is folder
students, or one student functioning, but it may not is deleted. The file residing
can associate with multiple require the same wheel. It inside that folder will also
teachers. may function with another get deleted at the time of
wheel as well. folder deletion.

2.2.GENERALIZATION
Generalization is a relationship that implements the concept of object orientation called
inheritance. This relationship occurs between two entities or objects, such that one entity is the
parent, and the other one is the child. The child inherits the functionality of its parent.
Generalization relationship is utilized in class, component, deployment, and use case diagrams
to specify that the child inherits actions, characteristics, and relationships from its parent.
The generalization relationship is incorporated to record attributes, operations, and
relationships in a parent model element so that it can be inherited in one or more child model
elements.

5
COURSE INSTRUCTOR Mr. SMITH WILLS

The parent model element can have as many children, and also, the child can have one or
more parents. But most commonly, it can be seen that there is one parent model element and
multiple child model elements. Generalization does not consist of names. Rather, it is
represented by a solid line with a hollow arrowhead pointing towards the parent model element
from the child model element.

Exercise 1:
Consider a generalization relationship between Vehicle and its subclasses Car and Bike:
 Vehicle is the parent class with attributes like speed and capacity.
 Car and Bike are child classes that inherit these attributes and may have additional
specific attributes or methods.

6
COURSE INSTRUCTOR Mr. SMITH WILLS

2.3.DEPENDENCY
Dependency depicts how various things within a system are dependent on each other. Thus,
this is the kind of relationship in which a coach (one element) is dependent on the player
(another element). It is used in class diagrams, component diagrams, deployment diagrams,
and use-case diagrams, which indicates that a change to the supplier necessitates a change to
the client.
Example:

Coaches and players are related in this way, where the coach depends on the performance data
or behaviour of players to make strategic decisions. We’d show this with a dashed line and an
open arrow.
Exercise 1:
Consider a Car class that depends on a class called Engine, the Car class uses the Engine class
to perform its functions, such as starting, stopping, and accelerating.

7
COURSE INSTRUCTOR Mr. SMITH WILLS
MODULE 02
INTRODUCTION TO UML (UNIFIED MODELING LANGUAGE)

1. INTRODUCTION
Unified Modelling Language (UML) is a standard language for specifying, visualizing,
constructing, and documenting the artifacts of software systems. UML was created by the
Object Management Group (OMG) and UML 1.0 specification draft was proposed to the OMG
in January 1997.
Although UML is generally used to model software systems, it is not limited within this
boundary. It is also used to model non-software systems as well. For example, the process flow
in a manufacturing unit, etc.
Like any other language, UML has its own syntax (symbols and sentence formation rules) and
semantics (meanings of symbols and sentences). However, UML is not a programming
language but tools which can be used to generate code in various languages using UML
diagrams. UML has a direct relation with object-oriented analysis and design. After some
standardization, UML has become an OMG standard.

1.1.GOALS OF UML
A picture is worth a thousand words, this idiom absolutely fits describing UML. Object
oriented concepts were introduced much earlier than UML. At that point of time, there were no
standard methodologies to organize and consolidate the object-oriented development. It was
then that UML came into picture.
There are a number of goals for developing UML but the most important is to define some
general-purpose modelling language, which all modelers can use and it also needs to be made
simple to understand and use.
UML diagrams are not only made for developers but also for business users, common people,
and anybody interested to understand the system. The system can be a software or no software
system. Thus, it must be clear that UML is not a development method rather it accompanies
with processes to make it a successful system. In conclusion, the goal of UML can be defined
as a simple modelling mechanism to model all possible practical systems in today’s complex
environment.

1.2.ROLE OF UML IN OBJECT ORIENTED DESIGN


UML is a modelling language used to model software and non-software systems. Although
UML is used for non-software systems, the emphasis is on modelling OO software applications.
Most of the UML diagrams discussed so far are used to model different aspects such as static,
dynamic, etc. Now whatever be the aspect, the artifacts are nothing but objects If we look into
class diagram, object diagram, collaboration diagram, interaction diagrams all would basically
be designed based on the objects.
Hence, the relation between OO design and UML is very important to understand. The OO
design is transformed into UML diagrams according to the requirement. Before understanding
the UML in detail, the OO concept should be learned properly. Once the OO analysis and design
is done, the next step is very easy. The input from OO analysis and design is the input to UML
diagrams.

8
COURSE INSTRUCTOR Mr. SMITH WILLS

1.3.UML MODELLING TYPES


UML diagrams represent two different views of a system model: Static (or structural) view
and Dynamic (or behavioural) view
 Static (or structural) view: This view emphasizes the static structure of the system using
objects, attributes, operations, and relationships.
Example:
Class diagram, Composite Structure diagram.
 Dynamic (or behavioural) view: This view emphasizes the dynamic behaviour of the
system by showing collaborations among objects and changes to the internal states of
objects.
Example:
Sequence diagram, Activity diagram, State Machine diagram.
Architectural model represents the overall framework of the system. It contains both
structural and behavioural elements of the system. Architectural model can be defined as the
blueprint of the entire system. Package diagram comes under architectural modelling.

1.4.UML DIAGRAMS OVERVIEW


UML 2.2 has 14 types of diagrams divided into multiple categories as shown in the figure
below.

9
COURSE INSTRUCTOR Mr. SMITH WILLS

 Structure diagrams show the things in the modelled system. In a more technical term,
they show different objects in a system.

 Behavioural diagrams show what should happen in a system. They describe how the
objects interact with each other to create a functioning system.

I. CLASS DIAGRAM
Class diagrams are the main building block of any object-oriented solution. It shows the
classes in a system, attributes, and operations of each class and the relationship between each
class. In most modelling tools, a class has three parts. Name at the top, attributes in the middle
and operations or methods at the bottom.
The first step of how to make a class diagram is simple, identify and describe the system you’re
modelling. This can be anything but to keep things straightforward and make the relationships
that we document easier to understand.
In a large system with many related classes, classes are grouped together to create class
diagrams. Different relationships between classes are shown by different types of arrows.
Below is an image of a class diagram.

10
COURSE INSTRUCTOR Mr. SMITH WILLS

Components of a class diagram


The standard class diagram is composed of three sections:
Upper section: Contains the name of the class. This section is always required, whether you
are talking about the classifier or an object.
Middle section: Contains the attributes of the class. Use this section to describe the qualities
of the class. This is only required when describing a specific instance of a class.
Bottom section: Includes class operations (methods). Displayed in list format, each operation
takes up its own line. The operations describe how a class interacts with data.
Member access modifiers
All classes have different access levels depending on the access modifier (visibility). Here are
the access levels with their corresponding symbols:
 Public (+)
 Private (-)
 Protected (#)
 Package (~)
 Derived (/)
 Static (underlined)
Member scopes
There are two scopes for members: classifiers and instances.
Classifiers are static members while instances are the specific instances of the class. If you are
familiar with basic OO theory, this isn't anything groundbreaking.
Additional class diagram components
Depending on the context, classes in a class diagram can represent the main objects,
interactions in the application, or classes to be programmed. To answer the question "What is
a class diagram in UML?" you should first understand its basic makeup.
Classes: A template for creating objects and implementing behaviour in a system. In UML, a
class represents an object or a set of objects that share a common structure and behaviour.
They're represented by a rectangle that includes rows of the class name, its attributes, and its
operations. When you draw a class in a class diagram, you're only required to fill out the top
row—the others are optional if you'd like to provide more detail.
Name: The first row in a class shape.
Attributes: The second row in a class shape. Each attribute of the class is displayed on a
separate line.
Methods: The third row in a class shape. Also known as operations, methods are displayed in
list format with each operation on its own line.
Signals: Symbols that represent one-way, asynchronous communications between active
objects.

11
COURSE INSTRUCTOR Mr. SMITH WILLS

Data types: Classifiers that define data values. Data types can model both primitive types and
enumerations.
Packages: Shapes designed to organize related classifiers in a diagram. They are symbolized
with a large tabbed rectangle shape.
Interfaces: A collection of operation signatures and/or attribute definitions that define a
cohesive set of behaviours. Interfaces are similar to classes, except that a class can have an
instance of its type, and an interface must have at least one class to implement it.
Enumerations: Representations of user-defined data types. An enumeration includes groups
of identifiers that represent values of the enumeration.
Objects: Instances of a class or classes. Objects can be added to a class diagram to represent
either concrete or prototypical instances.
Artifacts: Model elements that represent the concrete entities in a software system, such as
documents, databases, executable files, software components, etc.

II. COMPONENT DIAGRAM


A component diagram displays the structural relationship of components of a software
system. These are mostly used when working with complex systems with many components.
Components communicate with each other using interfaces. The interfaces are linked using
connectors. The image below shows a component diagram.

12
COURSE INSTRUCTOR Mr. SMITH WILLS

III. DEPLOYMENT DIAGRAM


A deployment diagram shows the hardware of your system and the software in that hardware.
Deployment diagrams are useful when your software solution is deployed across multiple
machines with each having a unique configuration. Below is an example deployment diagram

IV. OBJECT DIAGRAM


Object Diagrams, sometimes referred to as Instance diagrams are very similar to class
diagrams. Like class diagrams, they also show the relationship between objects but they use
real-world examples.
They show what a system will look like at a given time. Because there is data available in the
objects, they are used to explain complex relationships between objects.

13
COURSE INSTRUCTOR Mr. SMITH WILLS

V. PACKAGE DIAGRAM
As the name suggests, a package diagram shows the dependencies between different packages
in a system.

14
COURSE INSTRUCTOR Mr. SMITH WILLS

VI. USE CASE DIAGRAM


As the most known diagram type of the behavioural UML types, Use Case diagrams give a
graphic overview of the actors involved in a system, different functions needed by those actors
and how these different functions interact.
It’s a great starting point for any project discussion because you can easily identify the main
actors involved and the main processes of the system. You can create use case diagrams using
our tool and/or get started instantly using our use case templates.

VII. ACTIVITY DIAGRAM


An activity diagram visually represents the flow of actions or processes within a system. It
represents workflows in a graphical way. They can be used to describe the business workflow
or the operational workflow of any component in a system. Sometimes activity diagrams are
used as an alternative to State machine diagrams.

15
COURSE INSTRUCTOR Mr. SMITH WILLS

Activity Diagram Symbols


UML has specified a set of symbols and rules for drawing activity diagrams. Following are
the commonly used activity diagram symbols with explanations.

16
COURSE INSTRUCTOR Mr. SMITH WILLS

VIII. STATE MACHINE DIAGRAM


State machine diagrams are similar to activity diagrams, although notations and usage change
a bit. They are sometimes known as state diagrams or state chart diagrams as well. These are
very useful to describe the behaviour of objects that act differently according to the state they
are in at the moment. The State machine diagram below shows the basic states and actions.

17
COURSE INSTRUCTOR Mr. SMITH WILLS

IX. SEQUENCE DIAGRAM


Sequence diagrams in UML show how objects interact with each other and the order those
interactions occur. It’s important to note that they show the interactions for a particular scenario.
The processes are represented vertically and interactions are shown as arrows.
Sequence Diagram Notations
Lifeline
A lifeline represents an individual participant in the interaction.

18
COURSE INSTRUCTOR Mr. SMITH WILLS

Actor
An Actor is a type of role played by an entity that interacts with the subject (e.g., by
exchanging signals and data). An actor can also be an external to the subject (i.e., in the sense
that an instance of an actor is not a part of the instance of its corresponding subject). They
typically represent roles played by human users, external hardware, or other subjects.

Note
 An actor does not necessarily represent a specific physical entity but merely a particular
role of some entity.

 A person may play the role of several different actors and, conversely, a given actor
may be played by multiple different persons.
Activation
An activation is represented by a thin rectangle on a lifeline) represents the period during
which an element is performing an operation. The top and the bottom of the of the rectangle are
aligned with the initiation and the completion time respectively.

19
COURSE INSTRUCTOR Mr. SMITH WILLS

Messages
Call Message
A call message defines a particular communication between lifelines of an interaction, which
represents an invocation of operation of target lifeline.

Return Message
A return message defines a particular communication between lifelines of an interaction,
which represents the pass of information back to the caller of a corresponded former message.

Self-Message
A self-message defines a particular communication between lifelines of an interaction, which
represents the invocation of message of the same lifeline.

Recursive Message
A recursive message defines a particular communication between lifelines of an interaction,
which represents the invocation of message of the same lifeline. It's target points to an
activation on top of the activation where the message was invoked from.

20
COURSE INSTRUCTOR Mr. SMITH WILLS

Create Message
A create message defines a particular communication between lifelines of an interaction,
which represents the instantiation of (target) lifeline.

Destroy Message
A destroy message defines a particular communication between lifelines of an interaction,
which represents the request of destroying the lifecycle of target lifeline.

Duration Message
A duration message defines a particular communication between lifelines of an interaction,
which shows the distance between two-time instants for a message invocation.

Note
A note (comment) gives the ability to attach various remarks to elements. A comment carries
no semantic force, but may contain information that is useful to a modeler.

21
COURSE INSTRUCTOR Mr. SMITH WILLS

Example

22
COURSE INSTRUCTOR Mr. SMITH WILLS
MODULE 03
INTRODUCTION TO OBJECTED-ORIENTED DESIGN

1. INTRODUCTION
Object-oriented design (OOD) is the process of creating a software system or application
utilizing an object-oriented paradigm. This technique permits the creation of a software solution
based on object notion. OOD is an implementation of the object-oriented programming (OOP)
paradigm.
In the object-oriented design method, the system is considered a collection of objects (i.e.,
entities). The state is shared among the objects, and each object is responsible for its own state
data. Tasks designed for a specific purpose cannot refer to or update data from other objects.
Objects have internal data that represents their current state. Similar objects form a class. In
other words, every object belongs to a class.
Important Terms Related to Object-Oriented Design

I. C++ CLASSES/OBJECTS
C++ is an object-oriented programming language. Everything in C++ is associated with
classes and objects, along with its attributes and methods. For example: in real life, a car is an
object. The car has attributes, such as weight and colour, and methods, such as drive and brake.
Attributes and methods are basically variables and functions that belongs to the class. These are
often referred to as “class members”. A class is a user-defined data type that we can use in our
program, and it works as an object constructor, or a "blueprint" for creating objects.
Create a Class
To create a class, use the class keyword:
Example
Create a class called "MyClass":
class MyClass { // The class
public: // Access specifier
int myNum; // Attribute (int variable)

23
COURSE INSTRUCTOR Mr. SMITH WILLS

string myString; // Attribute (string variable)


};
 The class keyword is used to create a class called MyClass.
 The public keyword is an access specifier, which specifies that members (attributes and
methods) of the class are accessible from outside the class. You will learn more about
access specifiers later.
 Inside the class, there is an integer variable myNum and a string variable myString.
When variables are declared within a class, they are called attributes.
 At last, end the class definition with a semicolon ;.
Create an Object
In C++, an object is created from a class. We have already created the class named MyClass,
so now we can use this to create objects.
To create an object of MyClass, specify the class name, followed by the object name.
To access the class attributes (myNum and myString), use the dot syntax (.) on the object:
Example
Let’s create an object called "myObj" and access the attributes:
#include <iostream>
#include <string>
using namespace std;

class MyClass { // The class


public: // Access specifier
int myNum; // Attribute (int variable)
string myString; // Attribute (string variable)
};

int main() {
MyClass myObj; // Create an object of MyClass

// Access attributes and set values


myObj.myNum = 15;
myObj.myString = "Some text";

// Print values
cout << myObj.myNum << "\n";
cout << myObj.myString;
return 0;
}

24
COURSE INSTRUCTOR Mr. SMITH WILLS

II. INHERITANCE
In C++, it is possible to inherit attributes and methods from one class to another. We group the
"inheritance concept" into two categories:
 Derived class (child) - the class that inherits from another class
 Base class (parent) - the class being inherited from
C++ supports five types of inheritance i.e., Single Inheritance, Multilevel Inheritance,
Multiple Inheritance, Hierarchical Inheritance and Hybrid Inheritance. To inherit from a
class, use the : symbol.
Single Inheritance
Single inheritance is defined as the inheritance in which a derived class is inherited from the
only one base class.
In the example below, the Car class (child) inherits the attributes and methods from the Vehicle
class (parent):
Example
#include <iostream>
#include <string>
using namespace std;

// Base class
class Vehicle {
public:
string brand = "Ford";
void honk() {
cout << "Tuut, tuut! \n" ;
}
};

// Derived class
class Car: public Vehicle {
public:
string model = "Mustang";
};

int main() {
Car myCar;
myCar.honk();
cout << myCar.brand + " " + myCar.model;
return 0;
}

Note: Inheritance is useful for code reusability, reuse attributes and methods of an existing class
when you create a new class.

25
COURSE INSTRUCTOR Mr. SMITH WILLS

Multilevel Inheritance
A class can also be derived from one class, which is already derived from another class. In the
following example, MyGrandChild is derived from class MyChild (which is derived from
MyClass).
Example
#include <iostream>
using namespace std;

// Parent class
class MyClass {
public:
void myFunction() {
cout << "Some content in parent class." ;
}
};

// Child class
class MyChild: public MyClass {
};

// Grandchild class
class MyGrandChild: public MyChild {
};

int main() {
MyGrandChild myObj;
myObj.myFunction();
return 0;
}

Multiple Inheritance
A class can also be derived from more than one base class, using a comma-separated list:
#include <iostream>
using namespace std;

// Base class
class MyClass {
public:
void myFunction() {
cout << "Some content in parent class.\n" ;
}
};

// Another base class


class MyOtherClass {
public:

26
COURSE INSTRUCTOR Mr. SMITH WILLS

void myOtherFunction() {
cout << "Some content in another class.\n" ;
}
};

// Derived class
class MyChildClass: public MyClass, public MyOtherClass {
};

int main() {
MyChildClass myObj;
myObj.myFunction();
myObj.myOtherFunction();
return 0;
}

Hierarchical Inheritance
If more than one class is inherited from the base class, it's known as hierarchical inheritance.
In hierarchical inheritance, all features that are common in child classes are included in the base
class.
For example, Physics, Chemistry, Biology are derived from Science class. Similarly, Dog, Cat,
Horse is derived from Animal class.
Example
// C++ program to demonstrate hierarchical inheritance
#include <iostream>
using namespace std;

// base class
class Animal {
public:
void info() {
cout << "I am an animal." << endl;
}
};

// derived class 1
class Dog : public Animal {
public:
void bark() {
cout << "I am a Dog. Woof woof." << endl;
}
};

// derived class 2
class Cat : public Animal {
public:

27
COURSE INSTRUCTOR Mr. SMITH WILLS

void meow() {
cout << "I am a Cat. Meow." << endl;
}
};

int main() {
// Create object of Dog class
Dog dog1;
cout << "Dog Class:" << endl;
dog1.info(); // Parent Class function
dog1.bark();

// Create object of Cat class


Cat cat1;
cout << "\nCat Class:" << endl;
cat1.info(); // Parent Class function
cat1.meow();
return 0;
}

Output
Dog Class:
I am an animal.
I am a Dog. Woof woof.

Cat Class:
I am an animal.
I am a Cat. Meow.

Here, both the Dog and Cat classes are derived from the Animal class. As such, both the derived
classes can access the info() function belonging to the Animal class.
Hybrid Inheritance
Hybrid inheritance is a combination of more than one type of inheritance.
Example
#include <iostream>
using namespace std;
class A
{
protected:
int a;
public:
void get_a()
{
std::cout << "Enter the value of 'a' : " << std::endl;
cin>>a;

28
COURSE INSTRUCTOR Mr. SMITH WILLS

}
};

class B : public A
{
protected:
int b;
public:
void get_b()
{
std::cout << "Enter the value of 'b' : " << std::endl;
cin>>b;
}
};
class C
{
protected:
int c;
public:
void get_c()
{
std::cout << "Enter the value of c is : " << std::endl;
cin>>c;
}
};

class D : public B, public C


{
protected:
int d;
public:
void mul()
{
get_a();
get_b();
get_c();
std::cout << "Multiplication of a,b,c is : " <<a*b*c<< std::endl;
}
};
int main()
{
D d;
d.mul();
return 0;
}

29
COURSE INSTRUCTOR Mr. SMITH WILLS

Output
Enter the value of 'a' :
10
Enter the value of 'b' :
20
Enter the value of c is :
30
Multiplication of a,b,c is : 6000

III. POLYMORPHISM
Polymorphism means "many forms", and it occurs when we have many classes that are related
to each other by inheritance. As specified above, Inheritance lets us inherit attributes and
methods from another class. Polymorphism uses those methods to perform different tasks. This
allows us to perform a single action in different ways.
For example, think of a base class called Animal that has a method called animalSound().
Derived classes of Animals could be Pigs, Cats, Dogs, Birds - And they also have their own
implementation of an animal sound (the pig oinks, and the cat meows, etc.):
Example
// Base class
class Animal {
public:
void animalSound() {
cout << "The animal makes a sound \n";
}
};

// Derived class
class Pig : public Animal {
public:
void animalSound() {
cout << "The pig says: wee wee \n";
}
};

// Derived class
class Dog : public Animal {
public:
void animalSound() {
cout << "The dog says: bow wow \n";
}
};

30
COURSE INSTRUCTOR Mr. SMITH WILLS

Now we can create Pig and Dog objects and override the animalSound() method:
#include <iostream>
#include <string>
using namespace std;

// Base class
class Animal {
public:
void animalSound() {
cout << "The animal makes a sound \n";
}
};

// Derived class
class Pig : public Animal {
public:
void animalSound() {
cout << "The pig says: wee wee \n";
}
};

// Derived class
class Dog : public Animal {
public:
void animalSound() {
cout << "The dog says: bow wow \n";
}
};

int main() {
Animal myAnimal;
Pig myPig;
Dog myDog;

myAnimal.animalSound();
myPig.animalSound();
myDog.animalSound();
return 0;
}

31
COURSE INSTRUCTOR Mr. SMITH WILLS

Types of Polymorphism in C++


Polymorphism in C++ is categorized into two types. The figure below shows the types:

A. COMPILE TIME POLYMORPHISM


You invoke the overloaded functions by matching the number and type of arguments. The
information is present during compile-time. This means the C++ compiler will select the right
function at compile time.
Compile-time polymorphism is achieved through function overloading and operator
overloading.

i. FUNCTION OVERLOADING
Function overloading occurs when we have many functions with similar names but different
arguments. The arguments may differ in terms of number or type.
Example 1
#include <iostream>
using namespace std;
void test(int i) {
cout << " The int is " << i << endl;
}
void test(double f) {
cout << " The float is " << f << endl;
}
void test(char const *ch) {
cout << " The char* is " << ch << endl;
}
int main() {
test(5);
test(5.5);
test("five");
return 0;
}

32
COURSE INSTRUCTOR Mr. SMITH WILLS

Output
The int is 5
The float is 5.5
The char* is five

ii. OPERATOR OVERLOADING


In Operator Overloading, we define a new meaning for a C++ operator. It also changes how the
operator works. For example, we can define the + operator to concatenate two strings. We know
it as the addition operator for adding numerical values. After our definition, when placed
between integers, it will add them. When placed between strings, it will concatenate them.
Example 2
#include<iostream>
using namespace std;
class ComplexNum {
private:
int real, over;
public:
ComplexNum(int rl = 0, int ov = 0) {
real = rl;
over = ov;
}

ComplexNum operator + (ComplexNum const &obj) {


ComplexNum result;
result.real = real + obj.real;
result.over = over + obj.over;
return result;
}
void print() {
cout << real << " + i" << over << endl;
}
};
int main()
{
ComplexNum c1(10, 2), c2(3, 7);
ComplexNum c3 = c1+c2;
c3.print();
}

Output
13 + i9

33
COURSE INSTRUCTOR Mr. SMITH WILLS

B. RUNTIME POLYMORPHISM
This happens when an object’s method is invoked/called during runtime rather than during
compile time. Runtime polymorphism is achieved through function overriding. The function to
be called/invoked is established during runtime.

iii. FUNCTION OVERRIDING


Function overriding occurs when a function of the base class is given a new definition in a
derived class. At that time, we can say the base function has been overridden.
Example
#include <iostream>
using namespace std;
class Mammal {
public:
void eat() {

cout << "Mammals eat...";


}
};

class Cow: public Mammal {

public:
void eat() {

cout << "Cows eat grass...";


}
};
int main(void) {

Cow c = Cow();
c.eat();
return 0;
}
Output
Cows eat grass

iv. VIRTUAL FUNCTION


A virtual function is another way of implementing run-time polymorphism in C++. It is a
special function defined in a base class and redefined in the derived class. To declare a virtual
function, you should use the virtual keyword. The keyword should precede the declaration of
the function in the base class.
If a virtual function class is inherited, the virtual class redefines the virtual function to suit its
needs.

34
COURSE INSTRUCTOR Mr. SMITH WILLS

Example
#include <iostream>
using namespace std;
class ClassA {
public:
virtual void show() {
cout << "The show() function in base class invoked..." << endl;
}
};
class ClassB :public ClassA {
public:
void show() {
cout << "The show() function in derived class invoked...";
}
};
int main() {
ClassA* a;
ClassB b;
a = &b;
a->show();
}

Output
The show() function in derived class invoked...

Compile-Time Polymorphism Vs. Run-Time Polymorphism


Here are the major differences between the two:
COMPILE-TIME POLYMORPHISM RUN-TIME POLYMORPHISM
It’s also called early binding or static It’s also called late/dynamic binding or
polymorphism dynamic polymorphism
The method is called/invoked during compile The method is called/invoked during run time
time
Implemented via function overloading and Implemented via method overriding and
operator overloading virtual functions
Example of method overloading. Many Example of method overriding. Many
methods may have similar names but methods may have a similar name and the
different number or types of arguments same prototype.
Faster execution since the methods discovery Slower execution since method discoverer is
is done during compile time done during runtime.
Less flexibility for problem-solving is Much flexibility is provided for solving
provided since everything is known during complex problems since methods are
compile time. discovered during runtime.

35
COURSE INSTRUCTOR Mr. SMITH WILLS

Summary
 Polymorphism means to have many forms.
 It occurs when there is a hierarchy of classes related through inheritance.
 With polymorphism, a function can behave differently based on the object that
invokes/calls it.
 In compile-time polymorphism, the function to be invoked is established during
compile-time.
 In runtime polymorphism, the function to be invoked is established during runtime.
 Compile-time polymorphism is determined through function overloading and operator
overloading.
 In function overloading, there are many functions with similar names but different
arguments.
 The parameters can differ in number or type.
 In operator overloading, a new meaning is defined for C++ operators.
 Runtime polymorphism is achieved through function overriding.
 In function overriding, a derived class gives a new definition to a function defined in
the base class.

IV. ENCAPSULATION
Encapsulation is defined as binding together the data and the functions that manipulate them.
Thus, the wrapping up of data and information in a single unit.
The meaning of Encapsulation, is to make sure that "sensitive" data is hidden from users.
To achieve this, you must declare class variables/attributes as private (can’t be accessed from
outside the class). If you want others to read or modify the value of a private member, you can
provide public get and set methods.
Access Private Members
To access a private attribute, use public "get" and "set" methods:
Example
#include <iostream>
using namespace std;
class Employee {
private:
// Private attribute
int salary;

public:
// Setter
void setSalary(int s) {
salary = s;
}
// Getter
int getSalary() {
return salary;

36
COURSE INSTRUCTOR Mr. SMITH WILLS

}
};

int main() {
Employee myObj;
myObj.setSalary(50000);
cout << myObj.getSalary();
return 0;
}

Example explained
 The salary attribute is private, which have restricted access.
 The public setSalary() method takes a parameter (s) and assigns it to the salary
variable/attribute (salary = s).
 The public getSalary() method returns the value of the private salary attribute.
 Inside main(), we create an object of the Employee class. Now we can use the
setSalary() method to set the value of the private attribute to 50000. Then we call the
getSalary() method on the object to return the value.
Features of Encapsulation
Below are the features of encapsulation:
 We cannot access any function from the class directly. We need an object to access that
function that is using the member variables of that class.
 The function which we are making inside the class must use only member variables,
only then it is called encapsulation.
 If we don’t make a function inside the class which is using the member variable of the
class then we don’t call it encapsulation.
 Encapsulation improves readability, maintainability, and security by grouping data and
methods together.
 It helps to control the modification of our data members.
Encapsulation also leads to data abstraction. Using encapsulation also hides the data.
#include <iostream>
#include <string>
using namespace std;
class Person {
private:
string name;
int age;
public:
Person(string name, int age) {
this->name = name;
this->age = age;
}
void setName(string name) {
this->name = name;

37
COURSE INSTRUCTOR Mr. SMITH WILLS

}
string getName() {
return name;
}
void setAge(int age) {
this->age = age;
}
int getAge() {
return age;
}
};
int main() {
Person person("John Doe", 30);
cout << "Name: " << person.getName() << endl;
cout << "Age: " << person.getAge() << endl;
person.setName("Jane Doe");
person.setAge(32);
cout << "Name: " << person.getName() << endl;
cout << "Age: " << person.getAge() << endl;
return 0;
}

Data Hiding
Data hiding is a way of restricting the access of our data members by hiding the implementation
details. Encapsulation also provides a way for data hiding.
We can use access modifiers to achieve data hiding in C++.
Example 1: Data Hiding using the private specifier
#include <iostream>
using namespace std;
class Rectangle {
private:
// Variables required for area calculation
int length;
int breadth;

public:
// Setter function for length
void setLength(int len) {
length = len;
}
// Setter function for breadth
void setBreadth(int brth) {
breadth = brth;
}
// Getter function for length
int getLength() {

38
COURSE INSTRUCTOR Mr. SMITH WILLS

return length;
}
// Getter function for breadth
int getBreadth() {
return breadth;
}
// Function to calculate area
int getArea() {
return length * breadth;
}
};
int main() {
// Create object of Rectangle class
Rectangle rectangle1;
// Initialize length using Setter function
rectangle1.setLength(8);
// Initialize breadth using Setter function
rectangle1.setBreadth(6);
// Access length using Getter function
cout << "Length = " << rectangle1.getLength() << endl;
// Access breadth using Getter function
cout << "Breadth = " << rectangle1.getBreadth() << endl;

// Call getArea() function


cout << "Area = " << rectangle1.getArea();
return 0;
}

Example’s Explanation
 Here, we have made the length and breadth variables private.
 This means that these variables cannot be directly accessed outside of the Rectangle
class.
 To access these private variables, we have used public functions setLength(),
getLength(), setBreadth(), and getBreadth(). These are called getter and setter
functions.
 Making the variables private allowed us to restrict unauthorized access from outside the
class. This is data hiding.
 If we try to access the variables from the main() class, we will get an error.
Example 2
// Program to calculate the area of a rectangle
#include <iostream>
using namespace std;
class Rectangle {
public:
// Variables required for area calculation
int length;

39
COURSE INSTRUCTOR Mr. SMITH WILLS

int breadth;

// Constructor to initialize variables


Rectangle(int len, int brth) : length(len), breadth(brth) {}

// Function to calculate area


int getArea() {
return length * breadth;
}
};

int main() {
// Create object of Rectangle class
Rectangle rect(8, 6);

// Call getArea() function


cout << "Area = " << rect.getArea();
return 0;
}

Note: The getter and setter functions provide read-only or write-only access to our class
members. For example
getLength() // provides read-only access
setLength() // provides write-only access

Why Encapsulation?
 In C++, encapsulation helps us keep related data and functions together, which makes
our code cleaner and easy to read.
 It helps to control the modification of our data members.
 It helps to decouple the components of a system. For example, we can encapsulate code
into multiple bundles.
 These decoupled components (bundles) can be developed, tested, and debugged
independently and concurrently. And any changes in a particular component do not have
any effect on other components.
 We can also achieve data hiding using encapsulation. From example 2 listed above, if
we change the length and breadth variables into private or protected, then the access
to these fields is restricted.
 And, they are kept hidden from outer classes (Data Hiding)
Role of Access Specifiers in Encapsulation
Access specifiers facilitate Data Hiding in C++ programs by restricting access to the class
member functions and data members. There are three types of access specifiers in C++:
 Private: Private access specifier means that the members cannot be accessed (or
viewed) from outside the class.

40
COURSE INSTRUCTOR Mr. SMITH WILLS

 Protected: Protected access specifier means that the members cannot be accessed from
outside the class, however, they can be accessed in inherited classes.
 Public: Public access specifier means that the members are accessible from outside the
class.
Note: By default, all members of a class are private if you don't specify an access specifier:
Example
class MyClass {
int x; // Private attribute
int y; // Private attribute
};

V. ABSTRACTION
Data Abstraction is a process of providing only the essential details to the outside world and
hiding the internal details, i.e., representing only the essential details in the program. Data
Abstraction is a programming technique that depends on the separation of the interface and
implementation details of the program.
Let's take a real-life example of AC, which can be turned ON or OFF, change the temperature,
change the mode, and other external components such as fan, swing. But we don't know the
internal details of the AC, i.e., how it works internally. Thus, we can say that AC separates the
implementation details from the external interface.
C++ provides a great level of abstraction. For example, pow() function is used to calculate the
power of a number without knowing the algorithm the function follows.
In a C++ program if we implement a class with private and public members then it is an example
of data abstraction.
Data Abstraction can be achieved in two ways:
 Abstraction using classes
 Abstraction in header files
Abstraction using classes: An abstraction can be achieved using classes. A class is used to
group all the data members and member functions into a single unit by using the access
specifiers. A class has the responsibility to determine which data member is to be visible outside
and which is not.
Abstraction in header files: Another type of abstraction is in the header file. For example, the
pow() function available is used to calculate the power of a number without actually knowing
which algorithm the function uses to calculate the power. Thus, we can say that header files
hide all the implementation details from the user
Access Specifiers Implementing Abstraction:
 Public specifier: When the members are declared as public, members can be accessed
anywhere from the program.

41
COURSE INSTRUCTOR Mr. SMITH WILLS

 Private specifier: When the members are declared as private, members can only be
accessed only by the member functions of the class. Let's see a simple example of
abstraction in header files.
// program to calculate the power of a number.
#include <iostream>
#include<math.h>
using namespace std;
int main()
{
int n = 4;
int power = 3;
int result = pow(n,power); // pow(n,power) is the power function
std::cout << "Cube of n is : " <<result<< std::endl;
return 0;
}
Output:
Cube of n is : 64

In the above example, pow() function is used to calculate 4 raised to the power 3. The pow()
function is present in the math.h header file in which all the implementation details of the
pow() function is hidden.
Let's see a simple example of data abstraction using classes.
#include <iostream>
using namespace std;
class Sum
{
private: int x, y, z; // private variables
public:
void add()
{
cout<<"Enter two numbers: ";
cin>>x>>y;
z= x+y;
cout<<"Sum of two number is: "<<z<<endl;
}
};
int main()
{
Sum sm;
sm.add();
return 0;
}

42
COURSE INSTRUCTOR Mr. SMITH WILLS

Output
Enter two numbers:
3
6
Sum of two number is: 9

In the above example, abstraction is achieved using classes. A class 'Sum' contains the private
members x, y and z are only accessible by the member functions of the class.

VI. INTERFACES
An interface describes the behaviour or capabilities of a C++ class without committing to a
particular implementation of that class. The C++ interfaces are implemented using abstract
classes and these abstract classes should not be confused with data abstraction which is a
concept of keeping implementation details separate from associated data.
A class is made abstract by declaring at least one of its functions as pure virtual function. A
pure virtual function is specified by placing "= 0" in its declaration as follows.
class Box {
public:
// pure virtual function
virtual double getVolume() = 0;

private:
double length; // length of a box
double breadth; // breadth of a box
double height; // height of a box
};

The purpose of an abstract class (often referred to as an ABC) is to provide an appropriate base
class from which other classes can inherit. Abstract classes cannot be used to instantiate objects
and serves only as an interface. Attempting to instantiate an object of an abstract class causes a
compilation error.
Thus, if a subclass of an ABC needs to be instantiated, it has to implement each of the virtual
functions, which means that it supports the interface declared by the ABC. Failure to override
a pure virtual function in a derived class, then attempting to instantiate objects of that class, is
a compilation error.
Classes that can be used to instantiate objects are called concrete classes.
Example 1
Consider the following example where parent class provides an interface to the base class to
implement a function called getArea():
#include <iostream>
using namespace std;
// base class

43
COURSE INSTRUCTOR Mr. SMITH WILLS

class Shape
{
public:
// pure virtual function providing interface framework.
virtual int getArea() = 0;
void setWidth(int w)
{
width = w;
}

void setHeight(int h)
{
height = h;
}

protected:
int width;
int height;
};

// Derived classes
class Rectangle: public Shape
{
public:
int getArea()
{
return (width * height);
}
};

class Triangle: public Shape


{
public:
int getArea()
{
return (width * height)/2;
}
};

int main(void)
{
Rectangle Rect;
Triangle Tri;

Rect.setWidth(5);
Rect.setHeight(7);

// Print the area of the object.


cout << "Total Rectangle area: " << Rect.getArea() << endl;

44
COURSE INSTRUCTOR Mr. SMITH WILLS

Tri.setWidth(5);
Tri.setHeight(7);

// Print the area of the object.


cout << "Total Triangle area: " << Tri.getArea() << endl;

return 0;
}

Output
Enter the length and breadth of a rectangle:
23
20
Area of the rectangle is: 460
Enter the base and height of the triangle:
2
5
Area of the triangle is: 5

Example 2
#include <iostream.h>
using namespace std;
class Flower
{
public:
virtual void color()=0;
};
class Lily : Flower
{
public:
void color()
{
cout << "White Lily!!" << endl;
}
};
class Rose : Flower
{
public:
void color()
{
cout <<"Red Rose!!" << endl;
}
};
int main( ) {
Lily lly;
Rose rse;
lly.color();

45
COURSE INSTRUCTOR Mr. SMITH WILLS

rse.color();
return 0;
}

Output
White Lily!!
Red Rose!!

VII. CONSTRUCTORS
A constructor in C++ is a special method that is automatically called when an object of a class
is created. To create a constructor, we use the same name as the class, followed by parentheses
():
Thus, a constructor is a special method that is invoked automatically at the time of object
creation. It is used to initialize the data members of new objects generally. The constructor in
C++ has the same name as the class or structure. It constructs the values i.e., provides data for
the object which is why it is known as constructor. Constructors do not return value; hence they
do not have a return type.
Types of constructors
 Default constructor
 Parameterized constructor
 Overloaded constructor
 Constructor with default value
 Copy constructor
 Inline constructor
Default Constructors: Default constructor is the constructor which doesn’t take any argument.
It has no parameters. It is also called a zero-argument constructor.
// cpp program to illustrate the
// concept of constructors
#include <iostream>
using namespace std;
class construct {
public:
int a, b;

// default Constructor
construct()
{
a = 10;
b = 20;
}
};

int main()

46
COURSE INSTRUCTOR Mr. SMITH WILLS

{
// default constructor called automatically
// when the object is created
construct c;
cout << "a: " << c.a << endl << "b: " << c.b;
return 1;
}

Parameterized Constructors: It is possible to pass arguments to constructors. Typically, these


arguments help initialize an object when it is created. To create a parameterized constructor,
simply add parameters to it the way you would to any other function. When you define the
constructor’s body, use the parameters to initialize the object.
Note: When the parameterized constructor is defined and no default constructor is defined
explicitly, the compiler will not implicitly call the default constructor and hence creating a
simple object as
Student s;
Will flash an error

// cpp program to illustrate


// parameterized constructors
#include <iostream>
using namespace std;
class Point {
private:
int x, y;
public:
// parameterized Constructor
Point(int x1, int y1)
{
x = x1;
y = y1;
}

int getX() { return x; }


int getY() { return y; }
};

int main()
{
// constructor called
Point p1(10, 15);

// access values assigned by constructor


cout << "p1.x = " << p1.getX()
<< ", p1.y = " << p1.getY();
return 0;
}

47
COURSE INSTRUCTOR Mr. SMITH WILLS

Uses of Parameterized constructor


 It is used to initialize the various data elements of different objects with different values
when they are created.
 It is used to overload constructors.
Copy Constructor:
A copy constructor is a member function that initializes an object using another object of the
same class.
Whenever we define one or more non-default constructors (with parameters) for a class, a
default constructor (without parameters) should also be explicitly defined as the compiler will
not provide a default constructor in this case. However, it is not necessary but it’s considered
to be the best practice to always define a default constructor.
Copy constructor takes a reference to an object of the same class as an argument.
Sample(Sample &t)
{
id=t.id;
}

// implicit copy constructor


#include<iostream>
using namespace std;

class Sample
{ int id;
public:
void init(int x)
{
id=x;
}
void display()
{
cout<<endl<<"ID="<<id;
}
};

int main()
{
Sample obj1;
obj1.init(10);
obj1.display();

Sample obj2(obj1); //or obj2=obj1;


obj2.display();
return 0;
}

48
COURSE INSTRUCTOR Mr. SMITH WILLS

// explicit copy constructor


#include <iostream>
using namespace std;
class Sample
{
int id;
public:
void init(int x)
{
id=x;
}
Sample(){} //default constructor with empty body

Sample(Sample &t) //copy constructor


{
id=t.id;
}
void display()
{
cout<<endl<<"ID="<<id;
}
};
int main()
{
Sample obj1;
obj1.init(10);
obj1.display();

Sample obj2(obj1); //or obj2=obj1; copy constructor called


obj2.display();
return 0;
}

The prototype of the constructor looks like


<class-name> (list-of-parameters);

Constructor can be defined inside the class declaration or outside the class declaration
a. Syntax for defining the constructor within the class
<class-name>(list-of-parameters)
{
//constructor definition
}
b. Syntax for defining the constructor outside the class
<class-name>: :<class-name>(list-of-parameters)
{
//constructor definition
}

49
COURSE INSTRUCTOR Mr. SMITH WILLS

Example 1
// Example: defining the constructor within the class
#include<iostream>
using namespace std;
class student
{
int rno;
char name[50];
double fee;
public:
student()
{
cout<<"Enter the RollNo:";
cin>>rno;
cout<<"Enter the Name:";
cin>>name;
cout<<"Enter the Fee:";
cin>>fee;
}
void display()
{
cout<<endl<<rno<<"\t"<<name<<"\t"<<fee;
}
};
int main()
{
student s; //constructor gets called automatically when we create the object of the class
s.display();
return 0;
}

Example 2
// Example: defining the constructor outside the class
#include<iostream>
using namespace std;
class student
{
int rno;
char name[50];
double fee;
public:
student();
void display();

}
student::student()
{
cout<<"Enter the RollNo:";

50
COURSE INSTRUCTOR Mr. SMITH WILLS

cin>>rno;
cout<<"Enter the Name:";
cin>>name;
cout<<"Enter the Fee:";
cin>>fee;
}

void student::display()
{
cout<<endl<<rno<<"\t"<<name<<"\t"<<fee;
}

int main()
{
student s;
s.display();
return 0;
}

Destructor
A destructor is also a special member function as a constructor. Destructor destroys the class
objects created by the constructor. Destructor has the same name as their class name preceded
by a tilde (~) symbol. It is not possible to define more than one destructor. The destructor is
only one way to destroy the object created by the constructor. Hence destructor can-not be
overloaded. Destructor neither requires any argument nor returns any value. It is automatically
called when the object goes out of scope. Destructors release memory space occupied by the
objects created by the constructor. In destructor, objects are destroyed in the reverse of object
creation.
The syntax for defining the destructor within the class
~ <class-name>()
{
}

The syntax for defining the destructor outside the class.


<class-name>: : ~ <class-name>(){}

Example 1
#include <iostream>
using namespace std;
class Test {
public:
Test() { cout << "\n Constructor executed"; }

~Test() { cout << "\n Destructor executed"; }

51
COURSE INSTRUCTOR Mr. SMITH WILLS

};
main()
{
Test t;
return 0;
}

Example 2
#include <iostream>
using namespace std;
class Test {
public:
Test() { cout << "\n Constructor executed"; }

~Test() { cout << "\n Destructor executed"; }


};

main()
{
Test t, t1, t2, t3;
return 0;
}

Characteristics of a Destructor
 Destructor is invoked automatically by the compiler when its corresponding constructor
goes out of scope and releases the memory space that is no longer required by the
program.
 Destructor neither requires any argument nor returns any value therefore it cannot be
overloaded.
 Destructor cannot be declared as static and const;
 Destructor should be declared in the public section of the program.
 Destructor is called in the reverse order of its constructor invocation.

52
COURSE INSTRUCTOR Mr. SMITH WILLS

VIII. EXCEPTION
When executing a C++ code, different errors can occur: coding errors made by the
programmer, errors due to wrong input, or other unforeseeable things. When an error occurs,
C++ will normally stop and generate an error message. The technical term for this is: C++ will
throw an exception (throw an error).
In C++ programming, exception handling is performed using try/catch statement. The C++
try block is used to place the code that may occur exception. The catch block is used to handle
the exception.
Try and Catch Statement
Exception handling in C++ consist of three keywords: try, throw and catch:
 The try statement allows you to define a block of code to be tested for errors while it is
being executed.
 The throw keyword throws an exception when a problem is detected, which lets us
create a custom error.
 The catch statement allows you to define a block of code to be executed, if an error
occurs in the try block.
The try and catch keywords come in pairs:
Algorithm
try {
// block of code to try
throw exception; // throw an exception when a problem arises
}
catch () {
// block of code to handle errors
}
Example 1
#include <iostream>
using namespace std;
int main() {
try {
int age = 15;
if (age >= 18) {
cout << "Access granted - you are old enough.";
} else {
throw (age);
}
}
catch (int myNum) {
cout << "Access denied - You must be at least 18 years old.\n";
cout << "Age is: " << myNum;
}
return 0;
}

53
COURSE INSTRUCTOR Mr. SMITH WILLS

Explanation
We use the try block to test some code: If the age variable is less than 18, we will throw an
exception, and handle it in our catch block.
In the catch block, we catch the error and do something about it. The catch statement takes a
parameter: in our example we use an int variable (myNum) (because we are throwing an
exception of int type in the try block (age)), to output the value of age.
If no error occurs (e.g., if age is 20 instead of 15, meaning it will be greater than 18), the catch
block is skipped:
Palindrome Program
A palindrome number is a number that is same after reverse. For example, 121, 34543, 343,
131, 48984 are the palindrome numbers.
Algorithm
Get the number from user
Hold the number in temporary variable
Reverse the number
Compare the temporary number with reversed number
If both numbers are same, print palindrome number
Else print not palindrome number

Let's see how a palindrome program in C++ works. In this program, we will get an input from
the user and check whether the number is a palindrome or not.
Example 2
#include <iostream>
using namespace std;
int main()
{
int n,r,sum=0,temp;
cout<<"Enter the Number=";
cin>>n;
temp=n;
while(n>0)
{
r=n%10;
sum=(sum*10)+r;
n=n/10;
}
if(temp==sum)
cout<<"Number is Palindrome.";
else
cout<<"Number is not Palindrome.";
return 0;
}

54
COURSE INSTRUCTOR Mr. SMITH WILLS

C++ Standard Exceptions


C++ provides a list of standard exceptions defined in <exception> which we can use in our
programs. These are arranged in a parent-child class hierarchy shown below –

Here is the small description of each exception mentioned in the above hierarchy:
No EXCEPTION & DESCRIPTION
1 std::exception
An exception and parent class of all the
standard C++ exceptions.
2 std::bad_alloc
This can be thrown by new.
3 std::bad_cast
This can be thrown by dynamic_cast.
4 std::bad_exception
This is useful device to handle unexpected
exceptions in a C++ program.
5 std::bad_typeid
This can be thrown by typeid

55
COURSE INSTRUCTOR Mr. SMITH WILLS

6 std::logic_error
An exception that theoretically can be
detected by reading the code.
7 std::domain_error
This is an exception thrown when a
mathematically invalid domain is used
8 std::invalid_argument
This is thrown due to invalid arguments.
9 std::length_error
This is thrown when a too big std::string is
created.
10 std::out_of_range
This can be thrown by the 'at' method, for
example a std::vector and
std::bitset<>::operator[]().
11 std::runtime_error
An exception that theoretically cannot be
detected by reading the code.
12 std::overflow_error
This is thrown if a mathematical overflow
occurs.
13 std::range_error
This is occurred when you try to store a value
which is out of range.
14 std::underflow_error
This is thrown if a mathematical underflow
occurs.

56

You might also like