0% found this document useful (0 votes)
3 views14 pages

Unit 2 oop

Unit 2 covers Object-Oriented Programming in C++, focusing on classes, objects, and access modifiers. It explains the structure of a class, how to create objects, and the significance of public, private, and protected access specifiers. Additionally, it discusses memory allocation for objects, the use of the 'this' pointer, and provides code examples to illustrate these concepts.

Uploaded by

Mahesh Mutnale
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views14 pages

Unit 2 oop

Unit 2 covers Object-Oriented Programming in C++, focusing on classes, objects, and access modifiers. It explains the structure of a class, how to create objects, and the significance of public, private, and protected access specifiers. Additionally, it discusses memory allocation for objects, the use of the 'this' pointer, and provides code examples to illustrate these concepts.

Uploaded by

Mahesh Mutnale
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Unit 2 :Object Oriented Programming

Class: A class in C++ is the building block, that leads to Object-Oriented programming. It is a
user-defined data type, which holds its own data members and member functions, which can be
accessed and used by creating an instance of that class. A C++ class is like a blueprint for an
object.
For Example: Consider the Class of Cars. There may be many cars with different names and
brand but all of them will share some common properties like all of them will have 4
wheels, Speed Limit, Mileage range etc. So here, Car is the class and wheels, speed limits,
mileage are their properties.

 A Class is a user defined data-type which has data members and member functions.
 Data members are the data variables and member functions are the functions used to
manipulate these variables and together these data members and member functions defines
the properties and behavior of the objects in a Class.
 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.
An Object is an instance of a Class. When a class is defined, no memory is allocated but when it
is instantiated (i.e. an object is created) memory is allocated.

To specify (define) a class in C++, use the class keyword followed by the class name, and
enclose the class body within curly braces terminated by a semicolon.
Basic Syntax
cpp
class ClassName {
// Access specifier (private, public, or protected)
// Data members (variables)
// Member functions (methods)
}; // <-- Do not forget this semicolon!
Complete Code Example
Here is a complete, working example showing how to declare a class, define its members, and
create an object from it:
cpp
#include <iostream>
#include <string>

// Specifying the class


class Car {
private:
// Hidden data members (Encapsulation)
string brand;
int year;

public:
// Constructor to initialize the object
Car(string b, int y) {
brand = b;
year = y;
}

// Member function to display data


void displayInfo() {
cout << "Brand: " << brand << ", Year: " << year << std::endl;
}
};

int main() {
// Creating an object (instance) of the Car class
Car myCar("Toyota", 2026);

// Calling the class method


[Link]();

return 0;
}

Defining Class and Declaring Objects


A class is defined in C++ using keyword class followed by the name of class. The body of class
is defined inside the curly brackets and terminated by a semicolon at the end.

Declaring Objects: 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;
Accessing data members and member functions: The data members and member functions of
class can be accessed using the dot(‘.’) operator with the object. For example if the name of
object is obj and you want to access the member function with the name printName() then you
will have to write [Link]() .
Accessing Data Members
The public data members are also accessed in the same way given however the private data
members are not allowed to be accessed directly by the object. Accessing a data member
depends solely on the access control of that data member.

// C++ program to demonstrate


// accessing of data members

#include <bits/stdc++.h>
using namespace std;
class Geeks
{
// Access specifier
public:

// Data Members
string geekname;

// Member Functions()
void printname()
{
cout << "Geekname is: " << geekname;
}
};

int main() {

// Declare an object of class geeks


Geeks obj1;

// accessing data member


[Link] = "Abhi";

// accessing member function


[Link]();
return 0;
}
Output:
Geekname is: Abhi
Member Functions in Classes
There are 2 ways to define a member function:
Inside class definition
Outside class definition
To define a member function outside the class definition we have to use the scope resolution ::
operator along with class name and function name.

// C++ program to demonstrate function


// declaration outside class

#include <bits/stdc++.h>
using namespace std;
class Geeks
{
public:
string geekname;
int id;

// printname is not defined inside class definition


void printname();

// printid is defined inside class definition


void printid()
{
cout << "Geek id is: " << id;
}
};

// Definition of printname using scope resolution operator ::


void Geeks::printname()
{
cout << "Geekname is: " << geekname;
}
int main() {

Geeks obj1;
[Link] = "xyz";
[Link]=15;

// call printname()
[Link]();
cout << endl;

// call printid()
[Link]();
return 0;
}
Output:
Geekname is: xyz
Geek id is: 15
Access Modifiers in C++
Last Updated :2 Jun, 2026




Access modifiers in C++ are keywords that control the accessibility of class members (data
members and member functions). They are an important part of encapsulation and data hiding,
allowing developers to restrict access to sensitive data and expose only the required
functionality.
 Control the visibility of class members.
 Help implement data hiding and encapsulation.
 Improve security and maintainability of code.
Types of Access Modifiers in C++
Access modifiers specify the access level of class members and define where they can be used.
C++ provides three access modifiers:
Public Specifier
The public access specifier allows class members to be accessed from anywhere in the program
through an object of the class.
 Public members can be accessed both inside and outside the class.
 Commonly used for functions and data that should be available to users of the class.
 Helps expose the required functionality of a class.
#include <iostream>
using namespace std;

class Student {
public:
string name;
};

int main() {
Student s;

// Accessing public member


[Link] = "John";

cout << [Link];

return 0;
}

Output
John
Explanation
 name is declared as a public member.
 It can be accessed directly using the object s.
 The value "John" is assigned and printed successfully.

Private Specifier
The private access specifier restricts access to class members so that they can only be accessed
within the class itself.
 Private members cannot be accessed directly outside the class.
 Used to hide sensitive data and implementation details.
 Helps achieve data hiding and encapsulation.
 By default, all members of a C++ class are private.
#include <iostream>
using namespace std;

class Employee {
private:

// salary and empId cannot be accessed


// from outside the Class
double salary;
int empID;

public:
string name; // Name can be accessed anywhere
Employee(string n, double s, int id) {
name = n;
salary = s;
empID = id;
}
};

int main() {
Employee emp("Fedrick", 50000, 101);
cout << "Name: " << [Link] << endl;
return 0;
}

Output
Name: Fedrick
Explanation
 salary and empID are declared as private members.
 These members cannot be accessed directly outside the class.
 name is declared as public, so it can be accessed using the object emp.
 Attempting to access [Link] or [Link] would result in a compilation error.

Protected Specifier
The protected access specifier allows class members to be accessed within the class and its
derived classes, while preventing direct access from outside the class.
 Accessible within the same class.
 Accessible in derived (child) classes through inheritance.
 Cannot be accessed directly using objects of the class.
 Commonly used when implementing inheritance.

#include <iostream>
using namespace std;

class Employee {
private:
double salary;

protected:
int empID;

public:
string name;

Employee(string n, double s, int id) {


name = n;
salary = s;
empID = id;
}
};

// Derived class (inherits from Employee)


class Manager : public Employee {
public:
Manager(string n, double s, int id) : Employee(n, s, id) {}

void showDetails() {
cout << "Manager Name: " << name << endl;
cout << "Manager ID: " << empID << endl;
}
};

int main() {
Employee emp("Fedrick", 50000, 101);
cout << "Employee Name: " << [Link] << endl;
Manager m("Rohit", 70000, 102);
[Link]();
return 0;
}

Output
Employee Name: Fedrick
Manager Name: Rohit
Manager ID: 102
Explanation
 empID is declared as a protected member of Employee.
 The derived class Manager can access empID directly inside its member function
showDetails().
 The private member salary remains inaccessible to the derived class.
 Protected members help share data and functionality with derived classes while keeping
them hidden from external code.
Defining member functions inside or outside the class definition
Member functions of a class can be defined either outside the class definition or inside the class
definition. In both the cases, the function body remains the same, however, the function header
is different.
Outside the Class: Defining a member function outside a class requires the function declaration
(function prototype) to be provided inside the class definition. The member function is declared
inside the class like a normal function. This declaration informs the compiler that the function is
a member of the class and that it has been defined outside the class. After a member function is
declared inside the class, it must be defined (outside the class) in the program.
The definition of member function outside the class differs from normal function definition, as
the function name in the function header is preceded by the class name and the scope resolution
operator (: :). The scope resolution operator informs the compiler what class the member belongs
to. The syntax for defining a member function outside the class is
class ClassName
{
private:
// Data members
public:
return_type functionName(parameters); // Function declaration
};
// Function definition outside the class
return_type ClassName::functionName(parameters)
{
// Function body
}
#include <iostream>
using namespace std;

class Student
{
private:
int roll;
string name;

public:
void getData(); // Function Declaration
void display(); // Function Declaration
};

// Function Definition Outside the Class


void Student::getData()
{
cout << "Enter Roll Number: ";
cin >> roll;

cout << "Enter Name: ";


cin >> name;
}

void Student::display()
{
cout << "\nStudent Details" << endl;
cout << "Roll Number: " << roll << endl;
cout << "Name: " << name << endl;
}

int main()
{
Student s;

[Link]();
[Link]();

return 0;
}
Enter Roll Number: 101
Enter Name: Rahul

Student Details
Roll Number: 101
Name: Rahul
Inside the Class: A member function of a class can also be defined inside the class. However,
when a member function is defined inside the class, the class name and the scope resolution
operator are not specified in the function header. Moreover, the member functions defined inside
a class definition are by default inline functions.
class ClassName
{
private:
// Data members

public:
return_type functionName(parameters)
{
// Function body
}
};

#include <iostream>
using namespace std;

class Student
{
private:
int roll;
string name;

public:
void getData(); // Function Declaration
void display(); // Function Declaration
};

// Function Definition Outside the Class


void Student::getData()
{
cout << "Enter Roll Number: ";
cin >> roll;

cout << "Enter Name: ";


cin >> name;
}

void Student::display()
{
cout << "\nStudent Details" << endl;
cout << "Roll Number: " << roll << endl;
cout << "Name: " << name << endl;
}
int main()
{
Student s;

[Link]();
[Link]();

return 0;
}
Enter Roll Number: 101
Enter Name: Rahul

Student Details
Roll Number: 101
Name: Rahul

Object Definition and Memory Allocation of Object in C++

Object Definition
Definition

An object is an instance of a class. It is a real-world entity that contains its own copy of the data
members and can access the member functions of the class.

 A class is a blueprint.
 An object is created from the class.
 Memory is allocated only when an object is created.

Syntax for Object Definition


ClassName objectName;
Example
#include <iostream>
using namespace std;

class Student
{
public:
int roll;

void display()
{
cout << "Roll Number = " << roll;
}
};

int main()
{
Student s1; // Object declaration
[Link] = 101;
[Link]();

return 0;
}
Output
Roll Number = 101

Memory Allocation of Object

Definition

When an object of a class is created, memory is allocated only for the data members of the
class. The member functions are stored only once in memory and are shared by all objects.
Key Points

 Memory is allocated when an object is created, not when the class is defined.
 Each object has its own copy of data members.
 All objects share the same copy of member functions.
 The size of an object depends on its data members (plus any compiler-added padding),
not on its member functions.

Syntax
ClassName object1, object2, object3;

Example
#include <iostream>
using namespace std;

class Student
{
public:
int roll;
float marks;

void display()
{
cout << "Roll = " << roll << endl;
cout << "Marks = " << marks << endl;
}
};

int main()
{
Student s1, s2;

[Link] = 1;
[Link] = 85.5;

[Link] = 2;
[Link] = 90.0;

[Link]();
[Link]();

return 0;
}
Output
Roll = 1
Marks = 85.5

Roll = 2
Marks = 90

Memory Representation
Class Student
-------------------------
Data Members:
roll
marks

Member Function:
display()
-------------------------

|
| Create Objects
V

+------------------+ +------------------+
| Object s1 | | Object s2 |
| roll = 1 | | roll = 2 |
| marks = 85.5 | | marks = 90.0 |
+------------------+ +------------------+
\ /
\ /
\ /
Shared Member Function
display()
'this' pointer in C++

The this pointer is a special pointer available inside every non-static member function of a
class. It points to the current object that invoked the member function.

 It is automatically created by the compiler.


 It stores the address of the current object.
 It is used to access the current object's data members and member functions.

Syntax
this->dataMember;

Example 1: Using this Pointer


#include <iostream>
using namespace std;

class Student
{
private:
int roll;

public:
void setData(int roll)
{
this->roll = roll;
}

void display()
{
cout << "Roll Number = " << this->roll << endl;
}
};

int main()
{
Student s1;

[Link](101);
[Link]();

return 0;
}
Output
Roll Number = 101

Example 2: Resolving Name Conflict


#include <iostream>
using namespace std;

class Employee
{
private:
int id;

public:
void setId(int id)
{
this->id = id;
}

void display()
{
cout << "Employee ID = " << id;
}
};

int main()
{
Employee e1;

[Link](1001);
[Link]();

return 0;
}
Output
Employee ID = 1001

Explanation:

 The parameter id and the data member id have the same name.
 this->id refers to the class data member.
 id refers to the function parameter.

Uses of this Pointer

1. Refers to the current object.


2. Resolves ambiguity between local variables and data members with the same name.
3. Returns the current object from a member function (return *this;).
4. Can be passed as an argument to another function.
5. Supports method chaining by returning *this.
Static Data Member & Member Function in C++”

You might also like