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

Unit 2 - Object Oriented Programming Using C++ (3rd MARCH 2025)

This document provides an overview of Object-Oriented Programming (OOP) concepts, contrasting it with Procedure-Oriented Programming. It covers key OOP principles such as classes, objects, inheritance, encapsulation, and polymorphism, emphasizing the importance of data and its protection. The document also includes examples of class and object creation in C++, illustrating how these concepts are implemented in programming.

Uploaded by

khushirmalviya
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)
5 views

Unit 2 - Object Oriented Programming Using C++ (3rd MARCH 2025)

This document provides an overview of Object-Oriented Programming (OOP) concepts, contrasting it with Procedure-Oriented Programming. It covers key OOP principles such as classes, objects, inheritance, encapsulation, and polymorphism, emphasizing the importance of data and its protection. The document also includes examples of class and object creation in C++, illustrating how these concepts are implemented in programming.

Uploaded by

khushirmalviya
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/ 57

Unit-II

IM–210B
PROGRAMMING USING
C++
Unit-II
ObjectOrientedProgramming-Introductionto
OOP-Meaning of Object-Meaning of Class–
LOOP, characteristics: Creation of new Data
Types, Giving importance to Class,
Inheritance, Encapsulation, Abstraction,
Polymorphism, Operator Overloading,
Function Overloading, Function Defining,
Software Reusability.
Procedure Oriented Programming
It is basically consists of writing a list of
instructions for the computer to follow, and
organizing these instructions into groups known
as functions.
Normally, use a flowchart to organize these
instruction or actions and represent the flow of
control from one action to another.
While we concentrate on the development of
functions very little attention is given to the data
that are being used by various functions.
But,
What happens to the data?
How are they affected by the functions that work
on them?
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.
In a large program it is very difficult to identify
what data is used by which function.
Incase we need to required an external
data structure, we also need to revise all
functions that access the data. This
provides an opportunities for bug to creep
in.
Another serious drawback with the
procedural approach is that it does not
model real world problems very well. This
is because functions are action – oriented
and do not really correspond to the
elements of the problem.
Characteristics of Procedure-
Oriented Programming
✓ Emphasis is on doing things (algorithms).
✓ Large Programs are divided into smaller
program knows 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.
✓ Employ top-down approach in program
design.
✓ So in the procedure-oriented approach the
problem is viewed as sequence of things
to done such as reading, calculating and
printing.
✓ A number of functions are written to
accomplish these tasks. The primary focus
is on functions.
Object oriented Programming
It is the most recent concept among
programming paradigms still means
different things to different people.
➢ The Major motivating factor in the
invention of object-oriented approach is to
remove some of the flaws encountered in
the procedural approach.
➢ Oops 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 functions.
➢ Oops allows decomposition of a problem into a
number of entities called object and then builds
data and function around these objects.
➢ The data of an object can be accessed only by
the functions associated with that object.
➢ The data of an object can be accessed only by
the functions associated with that object.
However functions of one object can access the
function of other objects.
Definition of OOPs
Object Oriented programming as an approach that
provides a way of modularizing program by creating
partitioned memory area for both data and functions
that can be as tem used templates for creating copies of
such modules on demand.

An object is considered to be a partitioned area of


computer memory that stores data and set of operation
that can access that data.

Since the memory partitions are independent, the


objects can be used in a variety of different programs
without modifications.
Finally, OOPs is an approach to program
organization and development that attempts to
eliminate some of the pitfalls of conventional
programming methods by incorporating the best
of structured programming features with several
powerful new concepts.

It is a new way of organizing and developing


programs and has nothing to do with any
particular language.
Some of the striking features of oops are :
➢ Emphasis is on data rather than procedure.
➢ Programs are divided into what are known as
objects.
➢ Data structures are designing such that they
characterize the objects.
➢ Functions that operate on the data of an object
are tied together in the data structure.
➢ Data is hidden and cannot be accessed by
external functions.
➢ Objects may communicate with each other
through functions.
➢ New data and functions can be easily added
whenever necessary.
➢ Follows bottom-up approach in program design.
Basic Concepts of OOPs
Classes
Objects
Data Abstraction and Encapsulation
Inheritance
Polymorphism
Dynamic binding
Message Passing
Classes
◼ Object contains data, and code to manipulate that data.
◼ The entire set of data and code of an object can be
made a user-defined data type with the help of a class.
◼ Objects are variables of the type class. Once a class has
been defined, we can create any number of objects
belonging to that class.
◼ Each object is associated with the data of type class with
which they are created.
◼ A class is thus a collection of objects of similar type.
◼ Classes are user-defined data types and like built-in types
of a programming language.
◼ The syntax used to create an objects is no different than
the syntax used to create an integer objects in C.
Classes and objects are the two main aspects of
object-oriented programming.
Look at the following illustration to see the
difference between class and objects:

Class -> fruit


Objects -> Apple, Banana, Mango
Class-> Car
Objects-volvo, Audi, Toyota
So, a class is a template for objects, and an object is an
instance of a class.

When the individual objects are created, they inherit all the
variables and functions from the class.
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 color, 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)
string myString; // Attribute (string variable)
};

Example explained
•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 ;
common
Class per_det{
Char first_name, middle_name, last_name;
Name (First, Middle, Last)
Address (House no. street, landmark, city, state,
country)
Id proof
Contact (mobile, email)
Gender
Date of birth} stu, emp, cust, retailer, distru
Stu.per_det
Emp.per_det
Cust.per_det
Class student_details{
Stu.per_det
Admission document
admissiondate
Fee
Program name
Batch year
}
C++ Class Methods
◼ Methods are functions that belongs to the class.
◼ There are two ways to define functions that
belongs to a class:
• Inside class definition
• Outside class definition
◼ In the following example, we define a function
inside the class, and we name it "myMethod".
◼ Note: You access methods just like you access
attributes; by creating an object of the class and
using the dot syntax (.):
◼ Inside Example
◼ class MyClass { // The class
public: // Access specifier
void myMethod() { // Method/function defined
inside the class
cout << "Hello World!";
}
};

int main() {
MyClass myObj; // Create an object of MyClass
myObj.myMethod(); // Call the method
return 0;
}
◼ To define a function outside the class definition, you have to
declare it inside the class and then define it outside of the
class. This is done by specifiying the name of the class,
followed the scope resolution :: operator, followed by the
name of the function:
Outside Example
class MyClass { // The class
public: // Access specifier
void myMethod(); // Method/function
declaration
};
// Method/function definition outside the class
void MyClass::myMethod() {
cout << "Hello World!";
}
int main() {
MyClass myObj; // Create an object of
MyClass
myObj.myMethod(); // Call the method
return 0;
}
Parameters
◼ You can also add parameters:
Example
◼ #include <iostream>
using namespace std;
class Car {
public:
int speed(int maxSpeed);
};

int Car::speed(int maxSpeed) {


return maxSpeed;
}
int main() {
Car myObj; // Create an object of Car
cout << myObj.speed(200); // Call the method with an argument
return 0;
}
Objects
◼ Objects are the basic runtime entities in an object-oriented
system.

◼ It may represent a person, a place , a table of data or any


item that the program has to handle.

◼ It may also represent user-defined data such as vectors time


and lists.

◼ Programming problem is analyzed in terms of objects and the


nature of communication between them.

◼ Program objects should be chosen such that they match


closely with the real-world objects.
◼ Each object contains data and code to manipulate the data.

◼ Objects can interact without having to know details of each


others data or code.

◼ When a program is executed, the objects interact by sending


messages to one another.

◼ It is sufficient to know the type of message accepted and the


type of response returned by the objects.

◼ Objects take up space in the memory and have an associated


address like a record in Pascal, C, C++.
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 : Create an object called "myObj" and access the attributes:
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";
cout << myObj.myNum << "\n"; // Print attribute values
cout << myObj.myString;
return 0;
}
Multiple Objects
You can create multiple objects of one class:
Example : // Create a Car class with some attributes
class Car {
public:
string brand;
string model;
int year;
};
int main() {
Car carObj1; // Create an object of Car
carObj1.brand = "BMW";
carObj1.model = "X5";
carObj1.year = 1999;

Car carObj2; // Create another object of Car


carObj2.brand = "Ford";
carObj2.model = "Mustang";
carObj2.year = 1969;

// Print attribute values


cout << carObj1.brand << " " << carObj1.model << " " << carObj1.year << "\n";
cout << carObj2.brand << " " << carObj2.model << " " << carObj2.year << "\n";
return 0;
}
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
To inherit from a class, use the : symbol.
Why And When To Use "Inheritance"?
- It is useful for code reusability: reuse attributes
and methods of an existing class when you create a
new class.
◼ Inheritance is the process of creating a new class called
the derived class, from the existing class called the base
class.
◼ It supports the concepts of hierarchical classification.
◼ The principle behind this sort of division is that each
derived class shares common characteristics with the
class from which it is derived.
◼ In oops, the concept of inheritance provides the idea of
reusability. This means that we can add addition 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 features of both
the classes.
◼ The real appeal and power of the inheritance
mechanism is that it allows the programmer to reuse
a class that is almost, but not exactly, what they
wants and to tailor the class in such a way that it
does not introduce any undesirable side-effects into
the rest of the classes.
◼ Each sub-class defines only those features that are
unique to it.
◼ Without the use of classification, each class would
have to explicitly include all of its features.

◼ Multilevel Inheritance : A class can also be derived


from one class, which is already derived from another
class.
◼ Multiple Inheritance
◼ A class can also be derived from more than one base
class, using a comma-separated list:
Student student
Name
program
Batch year
Total sem Sem I
Fee Specialisation
Personal details
C++ Inheritance Access Specifiers

There are three specifiers available in C++.


Until now, we have only used public
(members of a class are accessible from
outside the class) and private (members can
only be accessed within the class). The third
specifier, protected, is similar to private, but
it can also be accessed in the inherited
class:
In the example below, the Car class (child) inherits the attributes and
methods from the Vehicle class (parent):
// 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;
}
Data Abstraction and Encapsulation
◼ Abstraction refers to the act representing essential
features without including the background details or
explanation.
◼ Classes use the concept of abstraction and are defined
as a list of abstract attributes such as size, weight and
cost and functions to operate on these attribution.
◼ It encapsulate all the essential properties of the objects
that are to be created.
◼ The attributes are sometimes called data members
because they hold information. The function that operate
on these data are sometimes called methods or member
functions.
Data encapsulation
◼ Data encapsulation is the most striking features of a
class.
◼ The data is not accessible to the outside world , only
those functions which are wrapped in the class can
access it.
◼ These functions provide the interface between the
objects data and the program.
◼ This insulation of the data from direct access by the
program is called data hiding or information hiding.
◼ Since the classes use the concept of data abstraction
they are known as abstracted data types.
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
(cannot 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.
Why Encapsulation?
• It is considered good practice to declare your class
attributes as private (as often as you can).
Encapsulation ensures better control of your data,
because you (or others) can change one part of the
code without affecting other parts
• Increased security of data
◼ 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;
}
};

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

◼ Polymorphism means "many forms", and it


occurs when we have many classes that
are related to each other by inheritance.
◼ 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.
◼ Polymorphism plays an important role in
allowing objects having different internal
structures to share the same external interface.
◼ This means that a general class of operations
may be accessed in the same manner even
though specific actions associated with each
operation may differ.
◼ Polymorphism is extensively used in
implementing inheritance.
◼ Polymorphism is an important oops concept. “An
operation may exhibit different behavior in
different instances.” The behavior depends upon
the types of data used in the operation.
◼ Example : Operation of addition for two numbers and operation will
generate sum.

Void add(int, int)


void add(int, int,int)
Void add(float,int)
void add(int,float)
Void add(str,str)*

*In this operand 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.

Using a single function name to perform different types of tasks is


known as function overloading. i.e. A single function name can be
used to handle different number and different types of arguments.
This is something similar to a particular word having several
different meaning depending on the context.
◼ Polymorphism is broadly divided into two parts : Static polymorphism and
Dynamic polymorphism.
◼ The first being static polymorphism exhibited by overloaded functions.
◼ It refers to an entity in different physical forms simultaneously.
◼ Static polymorphism involves binding of functions on the basis of number, type
and sequences of their arguments.
◼ The various types of parameters are specified in the function declaration, and
therefore the function can be bound to the calls at compile time.
◼ This form of association is called early binding . The term early binding stems
from the fact that when the program is executed, the calls are already bound
to the appropriate functions.
◼ The resolution is on the basis of number, type and sequence of arguments
declared for each form of the function, consider the following function
declarations :
void add(int,int);
void add(float,float);
If the function add() is invoked, the parameters passed to it will determine,
which version of the function will be executed. This resolution is done at
compile time.
Dynamic Polymorphism
◼ The second being dynamic polymorphism exhibited using late binding.
◼ Binding refers to the linking of a procedure call to the code to be
executed in response to the call.
◼ Dynamic binding means that the code associated with a given procedure
call is not known until the time of the call at runtime.
◼ It is associated with polymorphism and inheritance.
◼ It refers to an entity changing its form depending on the circumstances.
◼ A function is said to exhibit dynamic polymorphism when it exists in
more than one form and calls to its various forms are resolved
dynamically when the program is executed.
◼ The term late binding refers to the resolution of the function to their
associated methods at run-time instead of compile time.
◼ This feature increases the flexibility of the program b allowing the
appropriate method to be invoked, depending on the context.
◼ The compiler is unable to bind a call toa method since resolution
depends on the context of the call.
Message Passing
An object-oriented program consists of objects that communicate with each
other. The process of programming in an object-oriented language,
therefore involves the following basic steps :
Creating classes that define objects and their behavior.
Creating objects from class definitions and establishing communication
among objects.
Objects communicate with one another by sending and receiving
information much the same way as people pass messages to one another.
The concept of message passing make it easier to talk about building
systems that directly model or simulate their real-world counterparts.
A message for an object is a request for execution of a procedure, and
therefore will invoke a function (procedure) in the receiving object that
generates the desired result.
Message passing involve specifying the name of the objects, the name of
the function (message) and the information to be sent.
Objects have a life cycle. They can be created and destroyed.
Communication with an object is feasible as long as it is alive.
Function Overloading in C++
◼ Function overloading is a feature of object oriented programming where
two or more functions can have the same name but different parameters.
◼ When a function name is overloaded with different jobs it is called
Function Overloading.
◼ In Function Overloading “Function” name should be the same and the
arguments should be different.
◼ Function overloading can be considered as an example of polymorphism
feature in C++.
◼ Following is a simple C++ example to demonstrate function overloading.
◼ Function overloading is a C++ programming feature that allows us
to have more than one function having same name but different
parameter list. Here parameter list, it means the data type and
sequence of the parameters, for example the parameters list of a
function myfuncn(int a, float b) is (int, float) which is different from
the function myfuncn(float a, int b) parameter list (float, int).
Function overloading is a compile-time polymorphism. Now that we
know what is parameter list lets see the rules of overloading: we
can have following functions in the same scope.
sum(int num1, int num2)
sum(int num1, int num2, int num3)
sum(int num1, double num2)

The easiest way to remember this rule is that the parameters should qualify any one or more
of the following conditions, they should have different type, number or sequence of
parameters.

For example: These two functions have different parameter type:


sum(int num1, int num2) sum(double num1, double num2)

These two have different number of parameters:


sum(int num1, int num2) sum(int num1, int num2, int num3)

These two have different sequence of parameters:


sum(int num1, double num2) sum(double num1, int num2)

All of the above three cases are valid case of overloading. We can have any number of
functions, just remember that the parameter list should be different. For example:
int sum(int, int) double sum(int, int)

This is not allowed as the parameter list is same. Even though they have different return
types, its not valid.
Function overloading Example
#include <iostream>
using namespace std;
class Addition {
public:
int sum(int num1,int num2) {
return num1+num2;
}
int sum(int num1,int num2, int num3) {
return num1+num2+num3;
}
};
int main(void) {
Addition obj;
cout<<obj.sum(20, 15)<<endl;
cout<<obj.sum(81, 100, 10);
return 0;
}
Output:

35
191
Advantages of Function overloading

The main advantage of function overloading is to the improve


the code readability and allows code reusability.

In the example 1, we have seen how we were able to have more


than one function for the same task(addition) with different
parameters, this allowed us to add two integer numbers as well as
three integer numbers, if we wanted we could have some more
functions with same name and four or five arguments.
Imagine if we didn’t have function overloading, we either have
the limitation to add only two integers or we had to write
different name functions for the same task addition, this would
reduce the code readability and reusability.
#include <iostream>
using namespace std;

void print(int i) {
cout << " Here is int " << i << endl;
}
void print(double f) {
cout << " Here is float " << f << endl;
}
void print(char const *c) {
cout << " Here is char* " << c << endl;
}

int main() {
print(10);
print(10.10);
print("ten");
return 0;
}

Output:
Here is int 10
Here is float 10.1
Here is char* ten
Operator Overloading
In C++, we can make operators to work for user defined classes. This means C++ has
the ability to provide the operators with a special meaning for a data type, this ability is
known as operator overloading. For example, we can overload an operator ‘+’ in a class
like String so that we can concatenate two strings by just using +. Other example classes
where arithmetic operators may be overloaded are Complex Number, Fractional Number,
Big Integer, etc.
A simple and complete example
#include<iostream>
using namespace std;
class Complex {
private:
int real, imag;
public:
Complex(int r = 0, int i = 0) {real = r; imag = i;}
// This is automatically called when '+' is used with between two Complex objects

Complex operator + (Complex const &obj) {


Complex res;
res.real = real + obj.real;
res.imag = imag + obj.imag;
return res;
}
void print() { cout << real << " + i" << imag << '\n'; }
};

int main()
{
Complex c1(10, 5), c2(2, 4);
Complex c3 = c1 + c2;
c3.print();
}
Output:

12 + i9
Syntax for C++ Operator Overloading
To overload an operator, we use a special operator function. We define the
function inside the class or structure whose objects/variables we want the
overloaded operator to work with.

class className {
... .. ...
public
returnType operator symbol (arguments) {
... .. ...
}
... .. ...
};
Here,
returnType : is the return type of the function.
operator : is a keyword.
symbol : is the operator we want to overload. Like: +, <, -, ++, etc.
arguments : is the arguments passed to the function.
Operator Overloading in Unary Operators
Unary operators operate on only one operand. The increment operator ++ and decrement operator -- are
examples of unary operators.

Example1: ++ Operator (Unary Operator) Overloading


// Overload ++ when used as prefix
#include <iostream>
using namespace std;
class Count {
private:
int value;

public:
// Constructor to initialize count to 5
Count() : value(5) {}
// Overload ++ when used as prefix
void operator ++ () {
++value;
}
void display() {
cout << "Count: " << value << endl;
}
};
int main() {
Count count1;
// Call the "void operator ++ ()" function
++count1;
count1.display();
return 0;
}
Output

Count: 6

Here, when we use ++count1;, the void operator ++ () is


called. This increases the value attribute for the object
count1 by 1.

Note: When we overload operators, we can use it to work


in any way we like. For example, we could have used ++
to increase value by 100.
Difference between procedure and OOP?
◼ Procedural programming is about writing procedures or functions
that perform operations on the data, while object-oriented
programming is about creating objects that contain both data and
functions.

◼ Object-oriented programming has several advantages over


procedural programming:

• OOP is faster and easier to execute


• OOP provides a clear structure for the programs
• OOP helps to keep the C++ code DRY "Don't Repeat Yourself",
and makes the code easier to maintain, modify and debug
• OOP makes it possible to create full reusable applications with less
code and shorter development time
Benefits of OOPs
◼ Object oriented contributes to the solution of many problems
associated with the development and quality of software
products.
◼ The new technology promises greater programmer productivity,
better quality of software and lesser maintenance etc.
◼ The principal advantages are :
◼ Through inheritance, we can eliminated redundant code and
extend the use of existing class.
◼ We can build program from the standard working modules that
communicate with one another, rather than having to start
writing the code from scratch. This leads to saving of
development time and higher productivity.
◼ The principle of data binding helps the programmer to build
secure programs that can not be invaded by code in other parts
of the program.
◼ It is possible to have multiple instances of an object to
co-exist without any interface.
◼ It is possible to map objects in the problem domain to
those in the program.
◼ It is easy to partition the work in a project based on
object.
◼ The data-centered design approach enables is to capture
more details of a model in implementable form.
◼ Object-oriented systems can be easily upgraded from
small to large system.
◼ Message Passing techniques for communication
between objects makes the interface descriptions with
external systems such simpler.
◼ Software complexity can be easily managed.

You might also like