Unit 2 - Object Oriented Programming Using C++ (3rd MARCH 2025)
Unit 2 - Object Oriented Programming Using C++ (3rd MARCH 2025)
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.
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.
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);
};
// 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
*In this operand are strings, then the operation would produce a
third string by concatenation.
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.
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
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
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.
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