OOPS Unit 1 Notes
OOPS Unit 1 Notes
OOPS Unit 1 Notes
PROGRAMMING
Unit 1
Prepared By
S. Janani ,AP/CSE
SVCE.
What Are OOPS Concepts In C++?
➢ OOPs, or Object-oriented programming is an approach or a programming pattern where the
programs are structured around objects rather than functions and logic. It makes the data
partitioned into two memory areas, i.e., data and functions, and helps make the code flexible
and modular.
➢ Object-oriented programming mainly focuses on objects that are required to be manipulated.
In OOPs, it can represent data as objects that have attributes and functions.
➢ The earlier approaches to programming were not that good, and there were several
limitations as well. Like in procedural-oriented programming, you cannot reuse the code
again in the program, and there was the problem of global data access, and the approach
couldn’t solve the real-world problems very well.
➢ In object-oriented programming, it is easy to maintain the code with the help of classes and
objects. Using inheritance, there is code reusability, i.e., you don’t have to write the same
code again and again, which increases the simplicity of the program. Concepts like
encapsulation and abstraction provide data hiding as well.
Basic Object-Oriented Programming (OOPS) Concept in C++(16m)
There are some basic concepts that act as the building blocks of OOPs.
1. Classes
2. Objects
3. Abstraction
4. Encapsulation
5. Inheritance
6. Polymorphism
7. Dynamic Binding
1. Object
➢ An Object can be defined as an entity that has a state and behavior, or in other words,
anything that exists physically in the world is called an object. It can represent a dog, a
person, a table, etc.
➢ An object means the combination of data and programs, which further represent an entity.
#include <iostream>
using namespace std;
class Student {
public:
int id;//data member (also instance variable)
string name;//data member(also instance variable)
};
int main() {
Student s1; //creating an object of Student
s1.id = 201;
s1.name = "Sonoo Jaiswal";
cout<<s1.id<<endl;
cout<<s1.name<<endl;
return 0;
}
Example 2 of Class and Object
#include <iostream>
using namespace std; int main(void) {
class Student { Student s1; //creating an object of Student
public: Student s2; //creating an object of Student
int id;//data member (also instance variable) s1.insert(201, "Sonoo");
string name;//data member(also instance variable) s2.insert(202, "Nakul");
void insert(int i, string n) s1.display();
{ s2.display();
id = i; return 0;
name = n; }
}
void display()
{
cout<<id<<" "<<name<<endl;
}
};
3. Abstraction
Abstraction helps in the data hiding process. It helps in displaying the essential features without
showing the details or the functionality to the user.
It avoids unnecessary information or irrelevant details and shows only that specific part which the
user wants to see.
4. Encapsulation
The wrapping up of data and functions together in a single unit is known as encapsulation. It can be
achieved by making the data members' scope private and the member function’s scope public to
access these data members. Encapsulation makes the data non-accessible to the outside world.
5. Inheritance
Inheritance is the process in which two classes have an is-a relationship among each other and
objects of one class acquire properties and features of the other class. The class which inherits
the features is known as the child class, and the class whose features it inherited is called the
parent class. For example, Class Vehicle is the parent class, and Class Bus, Car, and Bike are
child classes.
6. Polymorphism
Polymorphism means many forms. It is the ability to take more than one form. It is a feature
that provides a function or an operator with more than one definition. It can be implemented
using function overloading, operator overload, function overriding, virtual function.
Advantages of OOPs
There are various advantages of object-oriented programming.
➢ OOPs provide reusability to the code and extend the use of existing classes.
➢ In OOPs, it is easy to maintain code as there are classes and objects, which helps in making it
easy to maintain rather than restructuring.
➢ It also helps in data hiding, keeping the data and information safe from leaking or getting
exposed.
➢ Object-oriented programming is easy to implement.
Access Specifiers
In C++, there are three access specifiers:
•public - members are accessible from outside the class
•private - members cannot be accessed (or viewed) from outside the class
•protected - members cannot be accessed from outside the class.
class MyClass {
public: // Public access specifier
int x; // Public attribute
private: // Private access specifier
int y; // Private attribute
};
int main() {
MyClass myObj;
myObj.x = 25; // Allowed (public)
myObj.y = 50; // Not allowed (private)
return 0;
}
// C++ program to demonstrate private
#include<iostream>
using namespace std;
class Circle
{ private:
double radius;
public:
double compute_area()
{
return 3.14*radius*radius;
}
};
int main()
{
Circle obj;
obj.radius = 1.5;
cout << "Area is:" << obj.compute_area();
return 0;
}
// C++ program to demonstrate private
While defining a contructor you must remeber that the name of constructor will be same
as the name of the class, and contructors will never have a return type.
Constructors can be defined either inside the class definition or outside class definition
using class name and scope resolution :: operator.
Example1 of Parameterized Constructors
class Cube
{
public:
int side;
Cube(int x)
{
side=x; 10 20 30
}
};
int main()
{
Cube c1(10);
Cube c2(20);
Cube c3(30);
cout << c1.side;
cout << c2.side;
cout << c3.side;
}
C++ Copy Constructor
void myFunction()
{
// code to be executed
}
Call a Function
Declared functions are not executed immediately. They are "saved for later use", and
will be executed later, when they are called.
To call a function, write the function's name followed by two parentheses () and a
semicolon ;
In the following example, myFunction() is used to print a text (the action), when it is
called:
Create a function
void myFunction() {
cout << "I just got executed!";
}
int main() {
myFunction(); // call the function
return 0;
}
// Function
void myFunction() {
cout << "I just got executed!";
}
Try it Yourself »
Friend Function in C++ (8m)
As we already know that in an object-oriented programming language, the members of the
class can only access the data and functions of the class but outside functions cannot access
the data of the class. There might be situation that the outside functions need to access the
private members of the class so in that case, friend function comes into the picture.
What is a friend function?
A friend function is a function of the class defined outside the class scope but it has the right
to access all the private and protected members of the class.
The friend functions appear in the class definition but friends are the member functions.
➢ The friend function is declared using friend keyword.
➢ It is not a member of the class but it is a friend of the class.
➢ As it is not a member of the class so it can be defined like a normal function.
➢ Friend functions do not access the class data members directly but they pass an object
as an argument.
➢ It is like a normal function.
➢ If we want to share the multiple class's data in a function then we can use the friend
function.
Characteristics of a Friend function:
•The function is not in the scope of the class to which it has been declared as a
friend.
•It cannot be called using the object as it is not in the scope of that class.
•It can be invoked like a normal function without using the object.
•It cannot access the member names directly and has to use an object name
and dot membership operator with the member name.
•It can be declared either in the private or the public part.
In the above declaration, the friend function is preceded by the keyword friend.
The function can be defined anywhere in the program like a normal C++ function.
The function definition does not use either the keyword friend or scope resolution
operator.
Example 1 Friend Function – Addition of 2Nos(8m)
#include <iostream> int main()
using namespace std; {
class Calculator Calculator c;
{ int firstNum, secondNum;
private: int first, second; cout << "Enter the first number: " << endl;
friend int addNumbers(Calculator, int i, int j); cin >> firstNum;
int Add() cout << "Enter the second number: " << endl;
{ cin >> secondNum;
return first + second; cout << "Sum: " << addNumbers(c, firstNum,
} secondNum) << endl;
}; }
int addNumbers(Calculator c, int firstNum, int
secondNum)
{
c.first = firstNum;
c.second = secondNum;
return c.Add();
}
C++ Overloading (Function and Operator) (16 m)
If we create two or more members having the same name but different in number or type of
parameter, it is known as C++ overloading. In C++, we can overload Methods, Constructors,
and Indexed properties It is because only these members have parameters.
Types of overloading in C++ are:
1. Function overloading
2. Operator overloading
There are times where the data to be entered is allocated at the time of execution. For example, a
list of employees increases as the new employees are hired in the organization and similarly
reduces when a person leaves the organization. This is called managing the memory. So now, let
us discuss the concept of dynamic memory allocation
Memory allocation
Reserving or providing space to a variable is called memory allocation. For storing the data,
memory allocation can be done in two ways -
➢ Static allocation or compile-time allocation - Static memory allocation means providing
space for the variable. The size and data type of the variable is known, and it remains
constant throughout the program.
➢ Dynamic allocation or run-time allocation - The allocation in which memory is allocated
dynamically. In this type of allocation, the exact size of the variable is not known in advance.
Pointers play a major role in dynamic memory allocation.
Why Dynamic memory allocation?
Dynamically we can allocate storage while the program is in a running state, but variables cannot
be created "on the fly". Thus, there are two criteria for dynamic memory allocation
To allocate the space dynamically, the operator new is used. It means creating a request
for memory allocation on the free store. If memory is available, memory is initialized,
and the address of that space is returned to a pointer variable.
Syntax
Pointer_variable = new data_type;
The pointer_varible is of pointer data_type. The data type can be int, float, string, char,
etc.
Example 1
int *m = NULL // Initially we have a NULL pointer
m = new int // memory is requested to the variable
It can be directly declared by putting the following statement in a line -
int *m = new int
Initialize memory
We can also initialize memory using new operator.
For example 2
Allocate a block of memory : We can also use a new operator to allocate a block(array) of a
particular data type. For example
int *arr = new int[10]
Here we have dynamically allocated memory for ten integers which also returns a pointer to the
first element of the array. Hence, arr[0] is the first element and so on.
Note
•The difference between creating a normal array and allocating a block using new normal arrays is
deallocated by the compiler. Whereas the block is created dynamically until the programmer
deletes it or if the program terminates.
•If there is no space in the heap memory, the new request results in a failure throwing an
exception(std::bad_alloc) until we use nonthrow with the new operator. Thus, the best practice is to
first check for the pointer variable.
Delete operator
We delete the allocated space in C++ using the delete operator.
Syntax
delete pointer_variable_name
Example 3
delete m; // free m that is a variable
delete [] arr; // Release a block of memory
Example 4 to Demonstrate Dynamic Memory Allocation
The program will show the use of new and delete
#include <iostream> // Request block of memory// using new operator
using namespace std; float *f = new float(75.25);
int main () cout<< "Value of f: " << *f <<endl;
{ // Pointer initialization to null // Request block of memory of size
int* m = NULL; // Request memory for the variable int size = 5;
m = new(nothrow) int; // using new operator int *arr = new(nothrow) int[size];
if (!m) if (!arr)
cout<< "allocation of memory failed\n"; cout<< "allocation of memory failed\n";
else else
{ {
// Store value at allocated address for (int i = 0; i< size; i++)
*m=29; arr[i] = i+1;
cout<< "Value of m: " << *m <<endl; cout<< "Value store in block of memory: ";
} for (int i = 0; i< size; i++)
cout<<arr[i] << " ";
}
// freed the allocated memory
delete m;
delete f;
// freed the block of allocated memory
delete[] arr;
return 0;
}
Output :
Value of m: 29
Value of f: 75.25
Value store in block of memory: 1 2 3 4 5
Static Member Functions (2m or 8m)
➢ We can define class members static using static keyword. When we declare a member of a class
as static it means no matter how many objects of the class are created, there is only one copy of
the static member.
➢ A static member is shared by all objects of the class. All static data is initialized to zero when the
first object is created, if no other initialization is present. We can't put it in the class definition but
it can be initialized outside the class as done in the following example by redeclaring the static
variable, using the scope resolution operator :: to identify which class it belongs to.
➢ By declaring a function member as static, you make it independent of any particular object of the
class. A static member function can be called even if no objects of the class exist and
the static functions are accessed using only the class name and the scope resolution operator ::.
➢ A static member function can only access static data member, other static member functions and
any other functions from outside the class.
➢ Static member functions have a class scope and they do not have access to the this pointer of the
class. You could use a static member function to determine whether some objects of the class
have been created or not.
What is the difference between static and non-static variables?
Static Variables:
A static variable is associated with the class has only one copy per class but not for each object. An
instance of a class does not have static variables.
Static variables can be accessed by static or instance methods
Memory is allocated when the class is loaded in context area at run time.
Non-Static Variables:
Non-static variables will have one copy each per object. Each instance of a class will have one copy
of non-static variables.
Instance variables can be accessed only by the instance methods.
Instance variables are allocated at compile time.
Eg: A static variable can be shared by all users for the current running system. It’s a globally available
value and can be used by all users.
Example 1 Static variable
#include <iostream> private:
using namespace std; double length; // Length of a box
class Box { double breadth; // Breadth of a box
public: static int objectCount; double height; // Height of a box
Box(double l = 2.0, double b = 2.0, double h = 2.0) };
{ cout <<"Constructor called." << endl;
// Initialize static member of class Box
length = l;
int Box::objectCount = 0;
breadth = b;
int main(void) {
height = h;
Box Box1(3.3, 1.2, 1.5); // Declare box1
// Increase every time object is created
Box Box2(8.5, 6.0, 2.0); // Declare box2
objectCount++;
cout << "Total objects: " << Box::objectCount <<
} endl;
double Volume() { return 0;
return length * breadth * height; }
}
Example 2 :Static Function Members static int getCount() {
#include <iostream> return objectCount;
using namespace std; }
class Box { private:
public: double length; // Length of a box
static int objectCount; double breadth; // Breadth of a box
// Constructor definition double height; // Height of a box
Box(double l = 2.0, double b = 2.0, double h = 2.0) };
{ int Box::objectCount = 0;
cout <<"Constructor called." << endl; int main(void) {
length = l; // Print total number of objects before creating object.
breadth = b; cout << "Inital Stage Count: " << Box::getCount() <<
height = h; endl;
// Increase every time object is created Box Box1(3.3, 1.2, 1.5); // Declare box1
objectCount++; Box Box2(8.5, 6.0, 2.0); // Declare box2
} // Print total number of objects after creating object.
double Volume() { cout << "Final Stage Count: " << Box::getCount() <<
return length * breadth * height; endl;
} return 0;
}
Applications :
1. Modify the passed parameters in a function: If a function receives a reference to a variable, it
can modify the value of the variable. For example, the following program variables are swapped
using references.
2. Avoiding a copy of large structures: Imagine a function that has to receive a large object. If
we pass it without reference, a new copy of it is created which causes wastage of CPU time and
memory. We can use references to avoid this.
3. In For Each Loop to modify all objects: We can use references in for each loop to modify
all elements.
4. For Each Loop to avoid the copy of objects: We can use references in each loop to avoid a
copy of individual objects when objects are large.
Proxy Classes : The Proxy class is basically the Proxy design pattern. In this pattern an object
provides a modified interface for another class. Let us see one example.
class BinArray {
int arr[10];
int & operator[](int i) {
//Put some code here
}
};
In this code, there is no condition checking. But we want the operator[] to complain if we put
something like arr[1] = 98. But this is not possible, because it is checking the index not the value. Now
we will try to solve this using proxy pattern.
What is Operator Overloading? (8m)
Using operator overloading in C++, you can specify more than one meaning for an operator in one
scope. The purpose of operator overloading is to provide a special meaning of an operator for a user-
defined data type.
With the help of operator overloading, you can redefine the majority of the C++ operators. You can
also use operator overloading to perform different operations using one operator.
Syntax
To overload a C++ operator, you should define a special function inside the Class as follows:
class class_name
{
... .. ...
public
return_type operator symbol (argument(s))
{
... .. ...
}
... .. ...
};
Can all C++ Operators be Overloaded?(2m) No. There are C++ operators that can’t be
overloaded.They include:
•:: -Scope resolution operator
•?: -ternary operator.
•. -member selector
•Sizeof operator
•* -member pointer selector
Different Approaches to Operator Overloading in C++
You can perform operator overloading by implementing any of the following types of functions:
1.Member Function
2.Non-Member Function
3.Friend Function
•The operator overloading function may be a member function when a Left operand is an object of the
Class.
•When the Left operand is different, the Operator overloading function should be a non-member
function.
You can make the operator overloading function a friend function if it needs to access the private and
protected class members.
Rules for Operator Overloading:
•You can specify more than one meaning for a C++ operator in one scope.
•This is called operator overloading.
•Operator overloading provides a special meaning of an operator for a user-defined data type.
•You can redefine the majority of C++ operators through operator overloading.
•Not all C++ operators can be overloaded.
•For an operator to be overloaded, at least one of the operands must be a user-defined object.
•Only existing operators can be overloaded. You cannot overload new operators.
Binary Operators and Unary Operators (2m)
The unary operators operate on a single operand and following are the
examples of Unary operators
The binary operators take two arguments and following are the examples of Binary operators. You
use binary operators very frequently like