Unit-1
Object Oriented Programming Concepts: Complexity in software - The need
for object-orientation – Abstraction – Encapsulation – Modularity –
Hierarchy.
Basic Elements of C++: Classes – Objects – Data members and member
functions – private and public access specifiers - Static members - Constructors
– Singleton class - Destructors - Friend Functions and Friend Classes - Array
of objects – Pointer to objects - this pointer – References – Dynamic memory
allocation - Namespaces.
What is OOP?
Object-Oriented Programming (OOP) is a programming paradigm that organizes code around
objects rather than functions and logic.
An object represents a real-world entity and contains:
● Data (variables / attributes)
● Behavior (functions / methods)
C++ is a multi-paradigm language, but it strongly supports OOP.
The need for Object-Oriented Programming (OOP) is:
1. To make programs easy to develop and understand.
2. To reuse code using classes and objects.
3. To improve security by hiding data (encapsulation).
4. To reduce program errors and make maintenance easier.
5. To handle large and complex software projects efficiently.
Core Concepts of OOP in C++
1. Abstraction
Abstraction in C++ is the process of hiding the implementation details and only showing the
essential details or features to the user.
In C++ abstraction is achieved using abstract classes (classes that have at least one pure
virtual function).
2. Encapsulation
Encapsulation is the process of bundling data and methods into a single unit (class) and
restricting direct access to some of its components. It acts as a protective shield for the
data.
Data is hidden from other classes and accessed only through public methods.
Achieved by declaring class variables as private, public, protected
Ensures data integrity and controlled access.
3. Inheritance
Inheritance is a mechanism in C++ where a class (derived) acquires the properties and
behaviors of another class (base), forming an "is-a" relationship.
Enables code reusability by inheriting data members and methods from the base class.
Achieved using : followed by an access specifier (public, private, protected).
Example: Dog, Cat, Cow can be derived classes of the Animal base class.
4. Polymorphism
The word polymorphism means having many forms, and it comes from the Greek words
poly (many) and morph (forms), this means one entity can take many forms.
In C++, polymorphism allows the same method or object to behave differently based on
the context.
Function overloading
Operator overloading
5. Message Passing
An object oriented program consists of a set of objects that communicate with each other. 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 involves specifying the name of the object, the name of the function (message) and
information to be sent.
Employee . Salary (name)
Employee-Object
Salary-Message
Name-Information
Advantage of OOP over Procedure-Oriented Programming Language.
By using objects and classes, you can create reusable components, leading to less
duplication and more efficient development.
It provides a clear and logical structure, making the code easier to understand, maintain,
and debug.
OOP encourages minimizing code repetition, leading to cleaner, more maintainable code.
By reusing existing code and creating modular components, OOP allows for quicker and
more efficient application development.
Modularity
Modularity is the process of dividing a large program into smaller parts called modules or
functions. Each module performs a specific task independently. It makes the program easier to
understand, test, debug and maintain.
Advantages of Modularity
Reduces complexity of programs.
Makes debugging easier.
Improves code reusability.
Helps in easy maintenance of software.
Different programmers can work on different modules.
Example in C++
#include <iostream>
using namespace std;
void add()
{
int a = 5, b = 3;
cout << "Sum = " << a + b;
}
int main()
{
add();
return 0;
}
In this example, add() is a separate module that performs addition.
Hierarchy
Hierarchy in C++ refers to the arrangement of classes from general class to specialized class
using inheritance. It helps in code reuse and establishes relationship between classes.
In hierarchy, the parent class properties are inherited by child classes.
Advantages of Hierarchy
Promotes code reusability.
Reduces duplication of code.
Makes programs organized and easy to understand.
Helps in extending existing classes.
Supports inheritance concept in OOP.
Example in C++
#include <iostream>
using namespace std;
class Animal
{
public:
void eat()
{
cout << "Animals eat food";
}
};
class Dog : public Animal
{
};
int main()
{
Dog d;
[Link]();
return 0;
}
Here, Animal is the parent class and Dog is the derived class. The Dog class inherits the function
eat() from Animal. This shows hierarchy in C++.
Class and Object in C++
Class – Definition
A class is a user-defined data type that acts as a blueprint for creating objects.
It contains data members (variables) and member functions (methods) that define the
properties and behavior of an object.
Syntax of Class
class ClassName {
access_specifier:
data_members;
member_functions;
};
Example:-
class item
{
int member;
float cost;
public:
void getldata (int a ,float b);
void putdata (void);
};
Object – Definition
An object is an instance of a class.
It represents a real-world entity and occupies memory when created.
Syntax of Object
ClassName objectName;
Example:
Item x;
ACCESSING CLASS MEMBER:
The public class members can be accessed through objects. But the private data of a class can be
accessed only through the member functions of that class.
Syntax:
object [Link]-name(actual arguments);
Example:- x. getdata(100,75.5);
Example Program
#include <iostream>
using namespace std;
class Student {
public:
int roll;
string name;
void display() {
cout << roll << " " << name << endl;
}
};
int main() {
Student s1; // Object creation
[Link] = 1;
[Link] = "Rahul";
[Link]();
return 0;
}
Static Member Function in C++
Definition
A static member function is a function that belongs to the class rather than to any specific
object. It can access only static data members of the class.
Characteristics
● Declared using the keyword static
● Called using class name
● Does not require an object
● Can access only static variables
● Does not have this pointer
Syntax
class ClassName {
static data_type function_name();
};
Calling Static Member Function
ClassName::function_name();
Example Program
#include <iostream>
using namespace std;
class Sample {
static int count;
public:
static void show() {
cout << "Count = " << count << endl;
}
};
int Sample::count = 10; // Static data member definition
int main() {
Sample::show(); // Calling static member function
return 0;
}
Constructor and Destructor in C++
Constructor Definition
A constructor is a special member function of a class that is automatically called when an
object is created.
It is used to initialize data members of the class.
Characteristics
● Name is same as class name
● Has no return type
● Called automatically
● Can be overloaded
Syntax of Constructor
class ClassName {
public:
ClassName() {
// constructor body
}
};
Example of Constructor
#include <iostream>
using namespace std;
class Student {
public:
int roll;
Student() { // Constructor
roll = 10;
cout << "Constructor called" << endl;
}
};
int main() {
Student s1;
cout << [Link] << endl;
return 0;
}
Types of Constructors
1. Default Constructor
A constructor with no arguments is called a default constructor.
Example
#include <iostream>
using namespace std;
class Demo
{
public:
Demo()
{
cout << "Default Constructor Called";
}
};
int main()
{
Demo d;
return 0;
}
2. Parameterized Constructor
A constructor that accepts arguments is called a parameterized constructor.
Example
#include <iostream>
using namespace std;
class Student
{
public:
int mark;
Student(int m)
{
mark = m;
}
};
int main()
{
Student s(95);
cout << [Link];
return 0;
}
3. Copy Constructor
A constructor that copies the values of one object into another object is called a copy constructor.
Example
#include <iostream>
using namespace std;
class Test
{
public:
int x;
Test(int a)
{
x = a;
}
Test(const Test &t)
{
x = t.x;
}
};
int main()
{
Test t1(10);
Test t2 = t1;
cout << t2.x;
return 0;
}
Destructor
Definition
A destructor is a special member function that is automatically called when an object is
destroyed.
It is used to release memory and resources.
Characteristics
● Name is class name preceded by ~
● Has no return type
● Cannot be overloaded
● Called automatically at program end
Syntax of Destructor
class ClassName {
public:
~ClassName() {
// destructor body
}
};
Example of Destructor
#include <iostream>
using namespace std;
class Student {
public:
Student() {
cout << "Constructor called" << endl;
}
~Student() { // Destructor
cout << "Destructor called" << endl;
}
};
int main() {
Student s1;
return 0;
}
Differences Between Constructor and Destructor
Construct Destruct
or or
initializes objects automatically. cleans up resources automatically.
Initializes object
Destroys
object
Called at object creation Called at object destruction
Same name as class
~ClassNa
me
Can be overloaded Cannot be overloaded
Friend Function
A friend function is a non-member function that is granted access to the private and protected
members of a class. It is declared inside the class using the keyword friend, but defined outside the
class.
Characteristics:
It is not a member of the class
It has access to private and protected data
Access is limited to only that function
Example Program:
#include <iostream>
using namespace std;
class Account {
private:
int accno ,balance;
public:
Account(int a, int b) {
accno = a;
balance = b;
}
friend void showAccount(Account obj);
};
void showAccount(Account obj) {
cout << "Account Number : " << [Link] << endl;
cout << "Balance : " << [Link] << endl;
}
int main() {
Account a1(1001, 25000);
showAccount(a1);
return 0;
}
Output:
Account Number : 1001
Balance : 25000
Friend Class
A friend class is a class whose all member functions are allowed to access the private and protected
members of another class. Friendship is granted at the class level.
Characteristics:
All member functions get access
Provides wider access than friend function
Used when close interaction between classes is required
Example Program:
#include <iostream>
using namespace std;
class Teacher; // Forward declaration
class Student {
private:
int marks;
void showMarks() {
cout << "Marks : " << marks << endl;
}
public:
Student(int m) {
marks = m;
}
// Friend class declaration
friend class Teacher;
};
class Teacher {
public:
void viewStudent(Student s) {
cout << "Marks : " << [Link] << endl;
[Link]();
}
};
int main() {
Student s1(85);
Teacher t1;
[Link](s1);
return 0;
}
Output:
Marks:85
Marks:85
Comparison Between Friend Function and Friend Class
Feature Friend Function Friend Class
Scope of access One function All functions of a class
Declaration friend void func(); friend class ClassName;
Access level Limited Wide
Usage When specific access is required When complete cooperation is needed
Array of Objects in C++
Definition
An array of objects in C++ is an array in which each element is an object of a class.
It allows storing and managing multiple objects of the same class using a single array name.
Why Array of Objects is Used
To handle data of many objects efficiently
Reduces code repetition
Useful when working with records like students, employees, etc.
Syntax
ClassName objectArray[size];
Example Program
#include <iostream>
using namespace std;
class Student {
int roll;
char name[20];
public:
void getData() {
cout << "Enter roll and name: ";
cin >> roll >> name;
}
void display() {
cout << roll << " " << name << endl;
}
};
int main() {
Student s[3]; // Array of objects
for(int i = 0; i < 3; i++) {
s[i].getData();
}
cout << "\nStudent Details:\n";
for(int i = 0; i < 3; i++) {
s[i].display();
}
return 0;
}
this Pointer in C++
Definition
This pointer is an implicit pointer available inside all non-static member functions of a class. It
holds the address of the calling object and is used to refer to the current object.
Why this Pointer is Needed
● To distinguish between data members and function parameters with the same name
● To return the calling object
● To pass the current object as a parameter to another function
Characteristics of this Pointer
● It is automatically created by the compiler
● It is a constant pointer
● Available only in non-static member functions
● Cannot be modified
Syntax
this->data_member;
Example Program
#include <iostream>
using namespace std;
class Student {
int roll;
public:
void setRoll(int roll) {
this->roll = roll; // Differentiates data member and parameter
}
void display() {
cout << "Roll No: " << roll << endl;
}
};
int main() {
Student s1;
[Link](10);
[Link]();
return 0;
}
Pointer to Objects
A pointer to an object is a pointer variable that stores the address of an object. It is used to access
object members using the arrow (->) operator.
Advantages
1. Saves memory.
2. Helps in dynamic object handling.
3. Used in object-oriented programming concepts.
Example
#include <iostream>
using namespace std;
class Student
{
public:
int mark = 95;
};
int main()
{
Student s;
Student *ptr = &s;
cout << ptr->mark;
return 0;
}
Here, ptr stores the address of objects
References
A reference is an alternative name for an existing variable. It is declared using & symbol.
Advantages
1. Avoids copying of variables.
2. Makes programs efficient.
3. Used in function arguments.
Example
#include <iostream>
using namespace std;
int main()
{
int a = 10;
int &b = a;
cout << b;
return 0;
}
Here, b is a reference to variable a.
Dynamic Memory Allocation
Dynamic memory allocation means allocating memory during runtime using new operator and
releasing memory using delete operator.
Advantages
1. Efficient memory usage.
2. Memory can be allocated when needed.
3. Useful for large programs.
Example
#include <iostream>
using namespace std;
int main()
{
int *ptr = new int;
*ptr = 25;
cout << *ptr;
delete ptr;
return 0;
}
Here, memory is allocated dynamically using new.
Namespaces
A namespace is used to avoid naming conflicts in C++. It groups related functions and variables
under one name.
Advantages
1. Avoids ambiguity in large programs.
2. Organizes code properly.
3. Helps in code management.
Example
#include <iostream>
using namespace std;
int main()
{
cout << "Welcome to C++";
return 0;
}
Here, std is the standard namespace that contains cout and other standard functions.
Singleton Class in C++
A Singleton class is a class that allows only one object to be created throughout the program.
It is used when only one instance of a class is needed, such as database connection, printer
manager, etc.
Features of Singleton Class
1. Only one object can be created.
2. Constructor is made private.
3. A static object is used inside the class.
4. Provides global access to the object.
Example of Singleton Class in C++
#include <iostream>
using namespace std;
class Singleton
{
private:
static Singleton *instance;
Singleton()
{
cout << "Object Created";
}
public:
static Singleton* getInstance()
{
if(instance == NULL)
{
instance = new Singleton();
}
return instance;
}
};
Singleton* Singleton::instance = NULL;
int main()
{
Singleton *s1;
s1 = Singleton::getInstance();
return 0;
}
Advantages of Singleton Class
1. Controls object creation.
2. Saves memory.
3. Provides a single global access point.
4. Useful in database and configuration management.