0% found this document useful (0 votes)
21 views52 pages

Chapter Four OOP Concepts in C++

Uploaded by

Abdi Nigatu
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)
21 views52 pages

Chapter Four OOP Concepts in C++

Uploaded by

Abdi Nigatu
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/ 52

Chapter Four

Fundamentals of Classes
Introduction
• Developments in software technology continue to be dynamic.
• New tools and techniques are announced in quick succession.
• This has forced the software engineers and industry to continuously look for new approaches
to software design and development, and they are becoming more and more critical in view
of the increasing complexity of software systems as well as the highly competitive nature of
the industry.
• These rapid advances appear to have created a situation of crisis within the industry.
• The following issues need to be addressed to face the crisis:
❖ How to represent real-life entities of problems in system design?
❖ How to ensure reusability and extensibility of modules?
❖ How to develop modules that are tolerant of any changes in future?
❖ How to improve software productivity and decrease software cost?
❖ How to improve the quality of software?
Procedure-Oriented Programming
❖ Procedural programming is a paradigm that organizes code into procedures,
also known as functions or routines, that execute a sequence of operations. It
focuses on the sequence of tasks to be done.
❖The main focus is on functions, variables, and the flow of execution. It treats
data and procedures as separate entities.
❖ The primary focus is on functions. The technique of hierarchical decomposition
has been used to specify the tasks to be completed for solving a problem.
Cont….
❖ Procedure oriented programming basically consists of writing a list of instructions
❖ for the computer to follow and organizing these instructions into groups known as
functions.
❖ Flowcharts are used to organize these actions and represent the flow of control
from one action to another.
❖ In a multi-function program, many important data items are placed as global so that
they may be accessed by all the functions.
❖ Each function may have its own local data. Global data are more vulnerable to an
inadvertent change by a function.
❖ In a large program it is very difficult to identify what data is used by
which function.
❖ In case we need to revise an external data structure, we also need to revise all
functions that access the data. This provides an opportunity for bugs to creep in.
❖ Another serious drawback with the procedural approach is that we do not model
real world problems very well.
❖ This is because functions are action-oriented and do not really corresponding to the
element of the problem.
Cont…
❖ Some Characteristics exhibited by procedure-oriented programming are:
❖ Emphasis is on doing things (algorithms).
❖ Large programs are divided into smaller programs known as functions.
❖ Most of the functions share global data.
❖ Data move openly around the system from function to function.
❖ Functions transform data from one form to another.
❖ Employs top-down approach in program design.
❑ Advantages:
❖ Simple and straightforward for small programs or scripts.
❖ Easy to understand, especially for beginners.
❖ Efficient for linear, sequential tasks.
❑ Disadvantages:
❖ Not well-suited for large, complex systems where data is tightly interwoven with functions.
❖ Code can become difficult to maintain as it grows.
❖ Lack of organization and reusability as the program size increases.
Object Oriented Paradigm
• Object-oriented programming is a paradigm that organizes code around objects,
which are instances of classes.
• These objects represent real-world entities and combine data (attributes) and
operations (methods) that can be performed on that data.
• This Approach is preferable for large, complex systems, especially when there is a
need to model real-world concepts.
• OOP is ideal for applications with more complex data interactions and when
scalability, maintainability, and reusability are crucial.

Object A Object B
Communication
DATA DATA

Functions Functions

DATA

Functions
Object Oriented Paradigm
❖ The major motivating factor in the invention of object-oriented approach is to
mitigate some of the flaws encountered in the procedural approach.

❖ OOP treats data as a critical element in the program development and does not allow it to
flow freely around the system.

❖ It ties data more closely to the function that operate on it and protects it from accidental
modification from outside function.

❖ Object-oriented programming is a paradigm based on the concept of "objects" that


encapsulate both data and the functions that operate on the data.

❖ The data of an object can be accessed only by the function associated with that object.

❖ However, function of one object can access the function of other objects.
Characteristics of OOP approach
❖ Some of the features of bottom-up programming are:
❖ Emphasis is on data rather than procedure.
❖ Programs are divided into what are known as objects.
❖ Data structures are designed such that they characterize the objects.
❖ Functions that operate on the data of an object are ties together in the data structure.
❖ Data is hidden and cannot be accessed by external function.
❖ Objects may communicate with each other through function.
❖ New data and functions can be easily added whenever necessary.
❖ Follows bottom-up approach in program design.
▪ Object-oriented programming is the most recent concept among programming paradigms and
still means different things to different people.
Basic Concepts of Object-Oriented Programming
• It is necessary to understand some of the concepts used extensively in object-oriented
programming. These include:
✓ Objects
✓ Classes
✓ Data abstraction and encapsulation
✓ Inheritance
✓ Polymorphism
✓ Dynamic binding
✓ Message passing

❑ Class:
✓ A class is a definition of objects of the same kind.
✓ It is a blueprint, template, or prototype that defines and describes the static attributes
and dynamic behaviors common to all objects of the same kind.
✓ The entire set of data and code of an object can be made a user-defined data type with the help
of class. In fact, objects are variables of the type class.
✓ Once a class has been defined, we can create any number of objects belonging to that class.
Data Types
❖ Data types specify the type of data that a variable can store.
❖ They determine the size, layout, and range of values that the variable can hold. There are several
categories of data types in C++:
A. Primitive Data Types
❖ Primitive data types are the basic data types that are built into the C++ language
B. Modifiers (to modify the size or range):

❖ Modifiers change the size or range of data types. These modifiers can be used with integer types (short,
long) and the char type.
C. Derived Data Types
❖ Derived data types are created from fundamental data types. These include arrays, pointers, functions, and
references.
D. User-Defined Data Types
❖ C++ allows programmers to define their own data types using struct, class, union, and enum
Data Types
❖Summary of Data types
Data Type Description Size (Typical)
int Integer numbers 4 bytes
short Smaller integer numbers 2 bytes
long Larger integer numbers 4 or 8 bytes
long long Very large integer numbers 8 bytes
float Single precision floating-point number 4 bytes
double Double precision floating-point number 8 bytes
long double Extended precision floating-point number 8 or 16 bytes
char Single character or small integer (ASCII) 1 byte
bool Boolean values (true or false) 1 byte
void Represents no value N/A
struct User-defined data structure Varies
class User-defined class with data and methods Varies
enum Enumeration type with named integer constants Varies
Class
❖ Class: A class in C++ is the building block that leads to Object-Oriented
programming.

❖A class is a blueprint or template for creating objects. It defines the properties


(data) and behaviors (methods or functions) that objects of the class will have.

❖ A C++ class is like a blueprint for an object.


❖ For Example: Consider the Class of Cars. There may be many cars with different names and
brand but all of them will share some common properties like all of them will have 4 wheels,
Speed Limit, Mileage range etc.

❖ So here, Car is the class and wheels, speed limits, mileage are their properties.
Cont’d
Key Characteristics of a Class:
❖Encapsulation: A class encapsulates data (attributes) and methods (functions) that
operate on that data.
❖Data Members: The variables within a class are called attributes or properties. These
define the state of an object created from the class.
❖Member Functions: The functions within a class are called methods. These define the
behavior of the objects.
❖ In the above example of class Car, the data member will be speed limit, mileage etc
and member functions can be apply brakes, increase speed etc.

❖ An Object is an instance of a Class. When a class is defined, no memory is allocated but


when it is instantiated (i.e. an object is created) memory is allocated.
Defining Class and Declaring Objects
❑ A class is defined in C++ using keyword class followed by the name of
class.
❑ The body of class is defined inside the curly brackets and terminated by a
semicolon at the end.
Cont.….

• A class can be visualized as a three-compartment box, as illustrated:


• Class name (or identifier): identifies the class.
• Data Members or Variables (or attributes, states, fields): contains the static attributes of
the class.
• Member Functions (or methods, behaviors, operations): contains the dynamic
operations of the class.
Cont.…
• A class encapsulates the static attributes (data) and dynamic behaviors (operations
that operate on the data) in a box.
• Class Members: The data members and member functions are collectively called class
members.
• A class is used to specify the form of an object and it combines data representation and
methods for manipulating that data into one neat package. The data and functions within a
class are called members of the class.
Objects
• An instance of a class. It is the actual entity created based on the class.
• They may represent a person, a place, a bank account, a table of data or any
item that the program must handle.
• Are run time entities of a class.
• When a program is executed, the objects interact by sending messages to one
another.
• For example, if “customer” and “account” are two object in a program, then the
customer object may send a message to the account object requesting for the bank
balance. Each object contain data, and code to manipulate data.
• Objects can interact without having to know details of each other’s data or code.
• It is a sufficient to know the type of message accepted, and the type of response
returned by the objects.
Class Definition
• Defining a class is defining a blueprint for a data type.
• A class definition starts with the keyword class followed by the class name; and the class
body, enclosed by a pair of curly braces.
• A class definition must be followed either by a semicolon or a list of declarations. For example,
we defined the Box data type using the keyword class as follows:
class Box
{
public:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
};
• The keyword public determines the access attributes of the members of the class that follow
it. A public member can be accessed from outside the class anywhere within the scope of
the class object.
• We can also specify the members of a class as private or protected.
Defining objects
• A class provides the blueprints for objects, so basically an object is created from
a class.
• We declare objects of a class with exactly the same sort of declaration that
we declare variables of basic types.
• The Following statements declare two objects of class Box:
• Box Box1; // Declare Box1 of type Box
• Box Box2; // Declare Box2 of type Box
• Both of the objects Box1 and Box2 will have their own copy of data members.
Class Scope
❖ Class scope refers to the visibility and access of class members (variables
and methods) within the class.
❖ There are three main access specifiers that define the scope of class
members:
❖ Public: Members declared as public are accessible from anywhere in the
program, even outside the class.
❖ Private: Members declared as private are only accessible from within the
class itself (including from member functions).
❖ Protected: Members declared as protected are accessible from within the
class and by derived classes (but not by other code)
Class Scope
#include <iostream>
using namespace std;
class Rectangle {
public:
int length, width; // public members, accessible from outside the class
private:
int area; // private member, accessible only inside the class Output
public:
void setArea() { Area : 50
area = length * width; // Valid, because area is a private member
}
void displayArea() {
cout << "Area: " << area << endl; }};
int main() {
Rectangle rect;
rect.length = 10; // Valid, because 'length' is public
rect.width = 5; // Valid, because 'width' is public
rect.setArea(); // Valid, sets area using the class's member function
rect.displayArea(); // Valid, displays the area
// rect.area = 50; // Error! 'area' is private and cannot be accessed directly
return 0;
}
Accessing the Data Members of a class
• The data members and member functions of class can be accessed using the
dot(‘.’) operator with the object.
❖ In this Example, a class called Box
having
❖ data members height, width and
length
❖ is created.
❖ Two objects box1 and box2 are created.
❖ The value of each data member is
initialized using object name followed
by dot operator with the corresponding
member name.
❖ Object_name.datamember_name;
❖ Finally, the volume of box is calculated.
❖ When we run the program we will get
❖ the following output:
❖ Volume of Box1=: 400
The Scope Resolution Operator (::)
❖ The scope resolution operator :: is used to define methods outside the class definition and to
access global variables when there is a name conflict.
❖ The Scope Resolution Operator (::) is used in C++ to define the scope of a variable.
❖ It is particularly useful when you need to specify where an identifier (like a variable or function)
belongs.
❖ This operator is most commonly used for the following purposes:
❖ Defining Class Member Functions Outside the Class Definition
❖ Accessing Global Variables when There’s a Name Conflict
❖ Accessing Static Members
❖ Referencing Base Class Members cout << "Member x: " << this->x << endl; // Member variable
#include <iostream> cout << "Global x: " << ::x << endl; // Global variable (using
using namespace std; scope resolution operator)
int x = 10; // Global variable }};
class MyClass { int main() {
public: MyClass obj; obj.x = 50; // Set the member variable 'x'
int x; // Local member variable obj.print();
void print() { return 0;
int x = 20; // Local variable inside function }
cout << "Local x: " << x << endl; // Local
variable
Accessing Static Members of a Class using ::
❖ Static members of a class are shared among all objects of the class. You can access them using the class
name and the scope resolution operator.
class Counter {
public:
static int count; // Static member variable
Counter() {
count++; // Increment the count each time an object is created Output
}
static void displayCount() { // Static member function can access static variable not
non static variable # it is called using the class name, not an object.
cout << "Count: " << count << endl;
}
};
// Initialize static member outside the class definition(not tied to any instance of class//
int Counter::count = 0;
int main() {
Counter obj1;
Counter obj2;
// Accessing static member function and variable using scope resolution operator
Counter::displayCount(); // Output: Count: 2
cout << "Static count: " << Counter::count << endl; // Output: Static count: 2
return 0;}// since 2 objects are created, count increased 2 times(0→1, then 1-→2)
Referencing Base Class Members using :: operator
❖In an inheritance hierarchy, the scope resolution operator can be used to refer to
members of the base class.
class Base {
public: Output
void show() {
cout << "Base class show()" << endl; Derived class show()
}}; Base class show()
class Derived : public Base {
public:
void show() {
cout << "Derived class show()" << endl;
}
void callBaseShow() {
Base::show(); // Calling the base class show function using the scope resolution operator
}};
int main() {
Derived obj;
obj.show(); // Derived class show()
obj.callBaseShow(); // Base class show()
}
Accessing the Data Members of a class
❖ Access control in C++ allows you to specify which members of a class can be
accessed outside the class.
❖ Public members are accessible from anywhere.
❖ Private members are only accessible within the class itself.
class MyClass {
private:
int x;
public:
void setX(int val) {
x = val; // Can access private member
}
int getX() {
return x; // Can access private member
}};
int main() {
MyClass obj;
obj.setX(10); // Public method accessing private data
cout << obj.getX(); // Output: 10
}
Defining member functions
• Class member function can be defined inside the class or outside the class.
❖ To define a member function outside the class definition we have to use the scope resolution ::
operator
along with class name and function name.
Return type ClassName:: memberfunction(parameter list)
{
Statements;
}

Example:

Output:
Constructors and destructors
• Objects generally need to initialize variables or assign dynamic memory
during their process of creation to become totally operative and to avoid
returning unexpected values during their execution
• For example, what would happen if in the previous example (in class member
definition)we called the function CalculateVolume() before initializing the value
for length, width and height?
• Probably an undetermined result since the members height, width and length would
have never been assigned a value.
• In order to avoid that, a class can include a special function: a constructor:
• That can be declared by naming a member function with the same name as the class.
• It is automatically called when an object of a class is created. It is used to
initialize the object, allocate resources, or set up default values for the
member variables.
▪ Constructors are special class members which are called by the compiler
every time an object of that class is instantiated.
▪ Constructors have the same name as the class and may be defined inside or
outside the class definition.
Cont…
Explanation of the above code:
• The code defines a Box class to calculate the area and volume of a box, using constructors
for initialization.
• Class Members: The class Box has three private integer members: width, height, and
length.
• These represent the dimensions of the box.
❑ Constructors:
• There are two constructors: Two-parameter constructor (Box(int, int)):Used to initialize
only width and height. Useful for calculating the area (length is not needed for area).
• Three-parameter constructor (Box(int, int, int)):Used to initialize length, width, and
height.Useful for calculating the volume.
• Member Functions:area(): Returns the area of the box's base (width * height).
• volume(): Returns the volume of the box (length * width * height).
• Constructor Definitions:Box::Box(int a, int b): Initializes width as a and height as
b.Box::Box(int a, int b, int c): Initializes length as a, width as b, and height as c.
Copy Constructors
Copy Constructor:
•A copy constructor is a special constructor that creates a new object as
a copy of an existing object.
•It is used when a new object is initialized from another object of the
same class.
•Example:
class MyClass {
public:
int x;
MyClass(int val) { // Parameterized constructor
x = val;
}
MyClass(const MyClass &obj) { // Copy constructor
x = obj.x; // Copy the value of x from the passed object
}
};
Destructors
❖ A destructor in C++ is a special member function of a class that is automatically
called when an object of that class is destroyed.
❖ The primary purpose of a destructor is to release any resources that the object
may have acquired during its lifetime, such as:
❖Deallocating dynamically allocated memory.
❖Closing file handles or network connections.
❖Releasing other system resources.
❖A destructor has the same name as the class, but it is prefixed with a tilde (~).
❖A destructor does not have a return type (not even void), and it cannot take any
parameters.
❖It is automatically called when an object goes out of scope or is explicitly deleted (in
case of dynamic memory allocation)
❖A destructor cannot accept arguments, so it is not possible to pass values to it.
Cont…
• The Destructor fulfills the opposite functionality of constructor.
• It is automatically called when an object is released from the memory, either:
• Because its scope of existence has finished (for example, if it was
defined as a localobject within a function and the function ends) or
• Because it is an object dynamically especially and it is released using
operator delete.
• The destructor must have the same name as the class with a tilde (~) as
prefix and it must return no value.
• The use of destructors is especially suitable when an object assigns dynamic
memory during its life and at the moment of being destroyed we want to
release the memory that it has used.
Cont….
Example:
Cont…
Explanation:
1.Class (CRectangle ):
❖ CRectangle uses dynamic memory allocation for the width and height, making it
❖ flexible but requiring a destructor to manage cleanup.
❖ The area() method calculates the area by multiplying the dereferenced width and
❖ height.
2.Constructor:
•Allocates memory for the width and height using new and assigns their values.
3.Destructor:
•Cleans up the dynamically allocated memory using delete to prevent memory leaks.
4.Main Function:
•Two rectangle objects (rect and rectb) are created with different dimensions.
•Their areas are calculated using the area() method and printed to the console.
Overloading Constructor
• Overloading constructor: a class can have more than one constructor that differ in the number or types of
parameters. It allows you to create objects in different ways depending on the arguments passed.
• Remember that the compiler will execute the one that matches at the moment at which a function
with that name is called. At the moment at which a class object is declared.
• In fact, in the cases where we declare a class and we do not specify any constructor the compiler
automatically assumes two overloaded constructors ("default constructor" and "copy constructor").
• For example, for the class:
class CExample {
public:
int a,b,c;
void multiply (int n, int m) { a=n;
b=m; c=a*b; };
};
void multiply (int n, int m, int k) { a=n; b=m;
K=c; int product=a*b*c; };
This Pointer
❖ This pointer is a special pointer that points to the current object of the class. It
is used to refer to the calling object.

❖ Example:
class Point {
public:
int x, y;
void setX(int x) {
this->x = x; // Using this pointer to refer to the current object
}
};
This Pointer
// Method to display dimensions of the box
void display() const {
cout << "Length: " << this->length << ", Width: " << this->width << endl;
}
};
int main() { Output
// Create two Box objects
Box box1(10, 5);
Box box2(8, 6);
// Display the dimensions of the boxes
cout << "Box 1 dimensions: ";
box1.display();
cout << "Box 2 dimensions: ";
box2.display();
// Compare the areas of the two boxes
box1.compare(box2);
// Calculate the area using the 'this' pointer
cout << "Area of Box 1: " << box1.calculateArea() << endl;
cout << "Area of Box 2: " << box2.calculateArea() << endl;
return 0;
}
Array of Objects in C++
▪ An array in C/C++ is a collection of similar data items stored at contiguous
memory locations and elements can be accessed randomly using indices of an
array.
▪ They can be used to store the collection of primitive data types such as int, float,
double, char, etc of any particular type.
▪ To add to it, an array in C/C++ can store derived data types such as structures,
pointers, etc.
▪ When a class is defined, only the specification for the object is defined; no
memory or storage is allocated.
▪ To use the data and access functions defined in the class, you need to create
objects.
▪ Syntax:
▪ ClassName ObjectName[number of objects];
▪ The Array of Objects stores objects.
▪ An array of a class type is also known as an array of objects.
Example#1:
❖ Storing more than one Employee data. Let’s assume there is an array of
objects for storing employee data emp[50].
Here is the C++ program for storing data of one Employee:
/ /C++ program to implement the above approach
Let’s understand the above example
❖ In the above example, a class named Employee with id and name is being
considered.
❖ The two functions are declared-
❖ getdata(): Taking user input for id and name.
❖ putdata(): Showing the data on the console screen.
❖ This program can take the data of only one Employee. What if there is a
requirement to add data of more than one Employee.
❖ Here comes the answer Array of Objects. An array of objects can be used
if there is a need to store data of more than one employee. Below is the C++
program to implement the above approach-
Only differ on main function from the above
int main()
{
// This is an array of objects having
// maximum limit of 30 Employees
Employee emp[30];
int n, i;
cout << "Enter Number of Employees - ";
cin >> n;
// Accessing the function
for(i = 0; i < n; i++)
emp[i].getdata();
cout << "Employee Data - " << endl;
// Accessing the function
for(i = 0; i < n; i++)
emp[i].putdata();
}
Explanation:
❖ In this example, more than one Employee’s details with an Employee id and name can be
stored.
❖ Employee emp[30] – This is an array of objects having a maximum limit of 30
Employees.
❖ Two for loops are being used-
✓ First one to take the input from user by calling emp[i].getdata() function.
✓ Second one to print the data of Employee by calling the function emp[i].putdata()
function.
❑ Advantages of Array of Objects:
▪ The array of objects represent storing multiple objects in a single name.
▪ In an array of objects, the data can be accessed randomly by using the index number.
▪ Reduce the time and memory by storing the data in a single variable.
Data Abstraction in C++
• Data abstraction refers to, providing only essential information to the outside world and
hiding their background details, i.e., to represent the needed information in program without
presenting the details.
• Data abstraction is a programming (and design) technique that relies on the separation of
interface and implementation.
• Let's take one real life example of a TV, which you can turn on and off, change the channel,
adjust the volume, and add external components such as speakers, VCRs, and DVD players,
BUT you do not know its internal details, that is, you do not know how it receives signals over
the air or through a cable, how it translates them, and finally displays them on the screen.
• Thus, we can say a television clearly separates its internal implementation from its external
interface and you can play with its interfaces like the power button, channel changer, and
volume control without having zero knowledge of its internals.
• C++ classes provides great level of data abstraction. They provide sufficient public methods to
the outside world to play with the functionality of the object and to manipulate object data,
i.e., state without actually knowing how class has been implemented internally.
Data Abstraction in C++
• Any C++ program where you implement a class with public and private members is an
example of data abstraction.
• When the code is compiled and executed, it
produces the following result:
Total 60
• class adds numbers together, and returns
the sum.
• The public members addNum and getTotal
are the interfaces to the outside world and
a user needs to know them to use the class.
• The private member total is something that
the user doesn't need to know about, but is
needed for the class to operate properly
Encapsulation
• Binding code and data together into a single unit is known as encapsulation.
• All C++ programs are composed of the following two fundamental elements:
• Program statements (code): This is the part of a program that performs actions and
they are called functions.
• Program data: The data is the information of the program which affected by the
program functions.
• Encapsulation is an Object Oriented Programming concept that binds together the data
and functions that manipulate the data, and that keeps both safe from outside
interference and misuse.
• Data encapsulation led to the important OOP concept of data hiding.
• C++ supports the properties of encapsulation and data hiding through the creation of user-
defined types, called classes.
• A class can contain private, protected and public members. By default, all items defined in
a class are private
Encapsulation
Example:
class Box
{
public:
double getVolume(void)
{
return length * breadth * height;
}
private:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
};
• The variables length, breadth, and height are private. This means that they can be accessed only by
other members of the Box class, and not by any other part of your program. This is one way
encapsulation is achieved.
• To make parts of a class public (i.e., accessible to other parts of your program), you must declare them
after the public keyword. All variables or functions defined after the public specifier are accessible by
all other functions in your program.
• Making one class a friend of another exposes the implementation details and reduces encapsulation.
The ideal is to keep as many of the details of each class hidden from all other classes as possible.
Inheritance
• Inheritance is the process by which objects of one class acquired the properties of objects
of another classes.
• When one object acquires all the properties and behaviors of the parent object it is called
inheritance.
• It provides code reusability and achieves runtime polymorphism.
• In OOP, the concept of inheritance provides the idea of reusability.
• This means that we can add additional features to an existing class without modifying it.
• This is possible by deriving a new class from the existing one.
• The new class will have the combined feature of both the classes
• A class derivation list names one or more base classes and has the form:
• class derived-class: access-specifier base-class
• Where access-specifier is one of public, protected, or private, and base-class
is the name of a previously defined class.
• If the access-specifier is not used, then it is private by default
Cont..,
• Example:

• When the code is compiled and


executed, it produces the following
result:
Total area: 35
Polymorphism
▪ Polymorphism is another important OOP concept. Polymorphism, a Greek term, means
the ability to take more than one form.
▪ When one task is performed by different ways, it is called polymorphism.
▪ It can be done by using function overloading and function overriding.
▪ For example, consider the operation of addition:
▪ For two numbers, the operation will generate a sum.
▪ If the operands are strings, then the operation would produce a third string by
concatenation.
▪ The process of making an operator to exhibit different behaviors in different instances
is known as operator overloading
Polymorphism example

You might also like