Chapter Four OOP Concepts in C++
Chapter Four OOP Concepts in C++
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.
❖ 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.
❖ 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.
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: