C++ Classes
Panchatcharam Mariappan
Associate Professor
Department of Mathematics and Statistics,
IIT Tirupati
Panchatcharam October 2025 1
Oops concepts
2
OOPS
✓ Programming Paradigms
▪ Procedural
• Modules, Data Structures, Procedures that Operate upon them
▪ Objectural:
• Objects which encapsulate data and behavior
• Messages passed between objects
▪ Functional
• Functions, Closures, Recursion, lists, …
Panchatcharam October 2025 3
OOPS
✓ Object Oriented Programming
✓ Programming paradigm or programming language mode
✓ Programs are organized around data or objects rather
than functions and logic
✓ It compartmentalizes data into objects or data fields
✓ It describes the object contents and its behaviour
through the declaration of classes or methods
✓ Encapsulation: Easier to manage, variables and states
are hidden behind well-defined boundaries
Panchatcharam October 2025 4
OOPS
✓ Easy to design software
✓ Easy to maintain the software
✓ Reusable software
Panchatcharam October 2025 5
What are Objects
✓ A data type
Stores Data
+ Operations defined to act on the data
✓ Tangible Entities (Physically exists in real world)
• Person, Student, Locker, Air Ticket, etc
✓ Intangible Entities (Exists logically in real world)
• Bank Account, Email, Reservation
✓ Interactions between objects define the system
operations
Panchatcharam October 2025 6
Abstraction
❖ Take a Bank Details or Your Mobile Phone or PC
✓ It is not necessary that everyone should know
everything about your account
✓ Manager/Administrator has a role
✓ Cashier/User has a role
✓ Think: A piece of code as black box
✓ Cannot See
✓ Do not need to see
✓ Do not want to see
✓ High Coding details
Panchatcharam October 2025 7
What are Objects
✓ Attributes or Data Attributes
✓ Characteristics or properties of an entity in a database table
✓ A named piece of data or variable
✓ Data members (class variables and instance variables)
❖ Example 2: Circle has
✓ Example 1: Student has Radius
Name Center
Roll Number
Marks ❖ Example 3: Rectangle has
Branch/discipline Sides/Edges
Vertices
Panchatcharam October 2025 8
What are Objects
✓ Methods or Procedural Attributes
✓ Attributes bound to functions/behavior/operators
✓ Example 1: Student has ❖ Example 2: Circle has
Average Marks Calculation Area
Decide Grades Circumference
❖ Example 3: Rectangle has
Area
Circumference
Panchatcharam October 2025 9
Messages
✓ A process by which class components interact
Send data to another object
Request data from another object
Request object to perform some behaviour
✓ Implemented as methods (not called functions)
Functions are process that are object independent
Methods are dependent on the state of the object
Panchatcharam October 2025 10
Abstraction
✓ Encapsulation implements the concept of abstraction
Details associated with object
End user could see the public interface, but
implementation are hidden
Encapsulated
Public Interface
Attributes
Methods
Panchatcharam October 2025 11
Encapsulation
✓ Attributes and methods are encapsulated within the logical
boundary of the object entity
In procedural paradigms, data and functions are typically
maintained as separate entities
In Objectural paradigms, each object has attributes (data)
and methods (functions) that operates upon those
attributes
Panchatcharam October 2025 12
Glance at a class
13
Class
✓ Classes
✓ Classes Bundling Data
A definition of objects of the same kind + Functionality
Basic unit of OOP
A blueprint, template or prototype that
encapsulates both static attributes and dynamic
behaviours within a box
Defines a public interface for using these boxes
easily reusable
Combines data structures and algorithms in the
same box
Panchatcharam October 2025 14
Class
✓ Classes
Bundling Data
✓ Classes + Functionality
A collection of functions and attributes
Attached to a specific name to represent an
abstract concept
✓ Classes
User-defined prototype for an object with
attributes and methods
Panchatcharam October 2025 15
Class
✓ Classes
Bundling Data
✓ Classes + Functionality
A collection of functions and attributes
Attached to a specific name to represent an
abstract concept
✓ Classes
User-defined prototype for an object with
attributes and methods
Panchatcharam October 2025 16
Classes
✓ A software item that contains variables and methods
✓ Object Oriented Design focuses on
▪ Encapsulation
• dividing the code into a public interface, and a private implementation of
that interface
▪ Polymorphism:
• the ability to overload standard operators so that they have appropriate
behavior based on their context
▪ Inheritance:
• the ability to create subclasses that contain specializations of their
parents
Panchatcharam October 2025 17
Instances
✓ View class/object as factories or templates
✓ An Individual Object of a certain class
✓ Each object instance takes all the properties of the class
from which it was created
Attributes Methods/Functions
Radius Area()
Abstract Circle Circumference()
Concept
Radius=6
Radius=3 Area()=113.1
Area()=28.27 Circumference()=37.7
Circumference()=18.85
Panchatcharam October 2025 18
Class Vs Instance of a Class
✓ class name is the type ✓ Instance is one specific object
➢ class circle(object) ➢ Circle C1;
✓ Defined generically ➢ Circle C2;
➢ area=pi*r*r ✓ Data varies between instances
✓ Defines data and methods ➢ [Link](5.0)
common across all ➢ [Link](10.0)
instances ➢ C1.r and C2.r are different
✓ Instance has the structure of
the class
➢ [Link]()➔78.5398
➢ [Link]()➔314.159
Panchatcharam October 2025 19
Class Vs Instance of a Class
Panchatcharam October 2025 20
Class Vs Instance of a Class
Concept Description Example
Blueprint describing what all circles
Class class Circle { ... };
have/do
Instance/Object Actual circle with its own radius Circle c1; Circle c2;
Data Each object stores its own radius [Link] = 5, [Link] = 10
All objects can call the same
Function [Link](), [Link]()
methods
Panchatcharam October 2025 21
OOP Terminologies
❖ Object
A unique instance of data structured defined by its class
Contains Data Members
Class Variables
Instance Variables
Methods
Panchatcharam October 2025 22
OOP Terminologies
❖ Class
User-defined prototype for an object
Set of attributes to characterize any object of the class
Attributes
Data Members(Class Variables, Instance Variables)
Methods
Accessed via dot notation
❖ Instance
An individual object of a certain class
❖ Instantiation
Creation of an instance of a class
Panchatcharam October 2025 23
OOP Terminologies
❖ Class Variable
Shared by all instance of a class
Defined within a class
Outside any of the class’ methods
Not use as frequently as instance variable
❖ Instance Variable
Defined inside a method
Belongs to only to the current instance of the class
Panchatcharam October 2025 24
OOP Terminologies
❖ Data Member
A class variable
Instance Variable
Holds data associated with a class and its objects
❖ Method
A special kind of function that is defined in a class
definition
Panchatcharam October 2025 25
OOP Terminologies
❖ Function Overloading
Assignment of more than one behaviour to a particular
function
❖ Operator Overloading
Assignment of more than one function to a particular
operator
❖ Inheritance
Transfer of the characteristic of a class to other classes
that are derived from it
Panchatcharam October 2025 26
OOP Terminologies
❖ Overriding
When inheriting from a class, we can alter behaviour of
the parent class by overriding function
Declaring functions in the subclass with the same name
More precedence over parent class
❖ Polymorphism
Two objects of different classes
Supports same set of functions
Attributes can be treated identically
Implementation are different, but appears to be same
Panchatcharam October 2025 27
Why Use OOP and Classes of Objects
❑ Do you know or care how a smartphone or TV or washing
machine or any electrical appliances or your own body??
No. As long as you are the user of the appliances and the
appliance functions well
Panchatcharam October 2025 28
Why Use OOP and Classes of Objects
❖ Group different object of the same type
Classes and objects are more like the real world
Mimic the real world
Minimize the semantic gap by modelling the real world
❖ Semantic Gap:
Difference Between the real world and the
representation in a computer
❖ Allow you to define an interface to some object and its
operations
Use it without knowing the internals
❖ Modularize the program into multiple objects that work
together, each has its own purpose
Panchatcharam October 2025 29
C++ classes
30
Syntax for Classes
class ClassName
{
//Data members
private:
varType1 var1;
varType2 var2;
varType3 *var3;
varType4 var4[100];
//Member Functions
public:
ClassName(varType1 var1, varType2 var2, varType3 *var3, varType4 var4[100]); //Constructor
Print();
void Function1();
varType1 Function2(varType2 var2);
varType2 Function3(varType3 *var);
}
Panchatcharam October 2025 31
Classes
class Course
{
private:
string code;
string name;
float Marks;
char Grade;
public:
Course(string c="MA0001",string n="AVBACA",float m=0.0,char G='S')
{
code=c;
name=n;
Marks=m;
Grade=G;
}
void CalculateGrade();
void Print();
};
Panchatcharam October 2025 32
Classes
class Course
{
private: Members of the Class
string code;
string name;
float Marks;
char Grade;
public:
Course(string c="MA0001",string n="AVBACA",float m=0.0,char G='S')
{
code=c;
name=n; Constructors of the Class
Marks=m;
Grade=G;
}
void CalculateGrade(); Functions of the Class
void Print();
};
Panchatcharam October 2025 33
Instance
class Course
{ int main()
{ Instance of the Class
private:
string code;
Members of the Class Course Course1("MA5191",
string name; "Programming Laboratory",95.0,'A');
float Marks; [Link]();
char Grade; [Link]();
public: return 0;
Course(string c="MA0001",string
n="AVBACA",float m=0.0,char G='S') }
{
code=c; Mapped to c, n, m and G
name=n; c->”MA5191”
Constructors of the Class
Marks=m; n->“Programming Laboratory”
Grade=G; m->95.0
} G->’A’
void CalculateGrade();
void Print(); Functions of the Class
}; Download the CPP File
Panchatcharam October 2025 34
Constructor
❖ A constructor in C++ is a special member function of a
class that is automatically called when an object is created.
❖ Its main purpose is to initialize the object’s data members.
❖ Has the same as the class
❖ Has no return type, not even void.
❖ Is automatically invoked when you create an object.
Panchatcharam October 2025 35
Constructor
❖ A constructor in C++ is a special member function of a
class that is automatically called when an object is created.
❖ Its main purpose is to initialize the object’s data members.
#include <iostream>
using namespace std;
class Student {
public: int main() {
string name; Student s1(“Raja", 20); // constructor
int age; called automatically
// Constructor
[Link]();
Student(string n, int a)
{ }
name = n;
age = a;
}
void display() {
cout << "Name: " << name << ", Age: "
<< age << endl;
}
};
Panchatcharam October 2025 36
Implicit vs Explicit Constructor Calls
❖ A constructor in C++ is a special member function of a
class that is automatically called when an object is created.
❖ Its main purpose is to initialize the object’s data members.
#include <iostream>
using namespace std;
int main() {
class Student {
public: Student s1(“Raja", 20); // implicit call
string name; Student s2=Student(“Ravi”,19);/Explicit call
int age; [Link]();
// Constructor
}
Student(string n, int a)
{
name = n;
age = a;
}
void display() { Download the CPP File
cout << "Name: " << name << ", Age: "
<< age << endl;
}
};
Panchatcharam October 2025 37
Default Constructor
❖ A constructor with no arguments.
class Box {
public:
int length;
Box() { // default constructor
length = 10;
}
};
Panchatcharam October 2025 38
Parametrized Constructor
❖ A constructor with no arguments.
class Box {
public:
int length;
Box(int l) { // constructor
length = l;
}
};
Panchatcharam October 2025 39
Copy Constructor
❖ Used to create a new object as a copy of an existing object.
class Box {
public:
int length;
Box(const Box &b) { // copy constructor
length = [Link];
}
};
Panchatcharam October 2025 40
Constructor Overloading
❖ Used to create a new object as a copy of an existing object.
class Rectangle {
public:
int width, height;
Rectangle() { width = 1; height = 1; } // default
Rectangle(int w, int h) { width = w; height = h; } // parameterized
};
Panchatcharam October 2025 41
Constructor with initialization list
❖ A faster and preferred way to initialize members.
class Point {
int x, y;
public:
Point(int a, int b) : x(a), y(b) {} // initialization list
};
Panchatcharam October 2025 42
Constructor
❖ Constructors cannot return a value.
❖ You can’t call a constructor like a normal function.
❖ If no constructor is defined, the compiler provides a default
one automatically.
❖ Constructors can be private, useful in design patterns like
Singleton.
Panchatcharam October 2025 43
Scope (::) Operator
❖ The :: (scope resolution operator) connects a name to its
scope — it tells the compiler where to find or define
something.
Panchatcharam October 2025 44
Scope (::) Operator
❖ When we declare a member function inside a class, we can
later define it outside using the :: operator.
Panchatcharam October 2025 45
:: Operator
functions are defined outside the class
class Course void Course::Print()
{
{ cout<<"Course Code : "<<this->code<<endl;
private: cout<<"Course Name : "<<this->name<<endl;
string code;
Members of the Class cout<<"Marks Scored : "<<this->Marks<<endl;
cout<<"Grade : "<<this->Grade<<endl;
string name; }
float Marks;
void Course::CalculateGrade()
char Grade; {
public: if(this->Marks>90)
this->Grade='S';
Course(string c="MA0001",string else if(this->Marks>80 && this->Marks<90)
n="AVBACA",float m=0.0,char G='S') this->Grade='A';
//Complete the rest
{ else
code=c; this->Grade='F';
name=n; Constructors of the Class }
Marks=m;
Grade=G; int main()
{
} Course Course1("MA5191", "Programming
void CalculateGrade(); Laboratory",95.0,'A');
void Print(); [Link]();
Only functions are declared [Link]();
return 0;
};
}
Panchatcharam October 2025 46
this → pointer
❖ In C++, every non-static member function of a class has
access to a special hidden pointer called this.
❖ It points to the object that is currently calling the function.
❖ Differentiate between class data members and local
variables with the same name.
❖ Return the object itself (for function chaining).
❖ Pass the current object as an argument to another
function.
Panchatcharam October 2025 47
this → pointer
❖ Think of this as the word “myself” inside the class.
Panchatcharam October 2025 48
this → pointer
functions are defined outside the class
class Course void Course::Print()
{
{ cout<<"Course Code : "<<this->code<<endl;
private: cout<<"Course Name : "<<this->name<<endl;
string code;
Members of the Class cout<<"Marks Scored : "<<this->Marks<<endl;
cout<<"Grade : "<<this->Grade<<endl;
string name; }
float Marks; “the name variable belonging to this object”.
void Course::CalculateGrade()
char Grade; {
public: if(this->Marks>90)
this->Grade='S';
Course(string c="MA0001",string else if(this->Marks>80 && this->Marks<90)
n="AVBACA",float m=0.0,char G='S') this->Grade='A';
//Complete the rest
{ else
code=c; this->Grade='F';
name=n; Constructors of the Class } “the Marks variable belonging to this object”.
Marks=m;
Grade=G; int main()
{
} Course Course1("MA5191", "Programming
void CalculateGrade(); Laboratory",95.0,'A');
void Print(); [Link]();
Only functions are declared [Link]();
return 0;
};
}
Panchatcharam October 2025 49
this → pointer
class Box {
int length;
public:
Box(int l=0) { length = l; }
Box& setLength(int l) {
this->length = l;
return *this; // return the current object
}
void show() { cout << "Length = " << length << endl; }
};
int main() {
Box b;
[Link](10).show(); // method chaining
}
Panchatcharam October 2025 50
friend function
class Vector
{
private:
int length;
double *values;
public:
Vector(int N=0, double=0); //Constructor
Vector(const Vector&); // copy constructor
~Vector(){ delete [] values; } // destructor is defined inline
Vector& operator=(const Vector&); // overload assignment
void LinSpace(double xl,double xu,int n); //Linspace generates the list of equidistant n points between
xl and xu
Vector operator+(const Vector &x); //+ operator overloading
friend Vector operator+(const Vector &x, const Vector &y); //To add two vector
friend Vector operator-(const Vector &x, const Vector &y); //Subtract x-y
friend Vector operator*(const Vector &x, double c); //c*x
friend Vector operator*(double c, const Vector &x); //x*yy
double& operator[](int i) const { return values[i]; } // eg v[i] = 10
double norm();
double norm2();
double norm(int p);
double infnorm();
int size() const { return length; } // return length of vector
void print(); //prints the vector
void save(char *); //prints the vector in a file
};
Panchatcharam October 2025 51
friend function
A friend function is a function that is not a member of a class but is allowed to access the class’s private
and protected members.
In short, it’s an outsider with special access granted by the class.
Normally, private members of a class cannot be accessed directly from outside.
But sometimes, we want two or more classes or a standalone function to work closely together and
share internal data.
Example use cases:
•Operator overloading (+, ==, etc.)
•Accessing data from two different classes simultaneously
•Debugging or utility functions that need internal details
Panchatcharam October 2025 52
friend function
A friend function is a function that is not a member of a class but is allowed to access the class’s private
and protected members.
In short, it’s an outsider with special access granted by the class.
Think of a friend function like a trusted guest —
It’s not part of the family (class),
but it’s trusted enough to enter private rooms (private data).
Panchatcharam October 2025 53
friend function
A friend function is a function that is not a member of a class but is allowed to access the class’s private
and protected members.
In short, it’s an outsider with special access granted by the class.
Rule Description
Declared using friend keyword Inside class definition
Not called with dot (.) operator Called like a normal function
Accesses private/protected data If declared as a friend
Friendship is not mutual If A is friend of B, B isn’t automatically friend of A
Friendship is not inherited Derived class doesn’t inherit friendship
Panchatcharam October 2025 54
friend function
A friend function is a function that is not a member of a class but is allowed to access the class’s private
and protected members.
In short, it’s an outsider with special access granted by the class.
Feature Friend Function Member Function
Belongs to class No Yes
Access to private data Yes (if declared friend) Yes
Called using object No Yes
Uses this pointer No Yes
Panchatcharam October 2025 55
friend function
class Vector
{
private:
int length;
double *values;
public:
Vector(int N=0, double=0); //Constructor
Vector(const Vector&); // copy constructor
~Vector(){ delete [] values; } // destructor is defined inline
Vector& operator=(const Vector&); // overload assignment
void LinSpace(double xl,double xu,int n); //Linspace generates the list of equidistant n points between xl and xu
Vector operator+(const Vector &x); //+ operator overloading
friend Vector operator+(const Vector &x, const Vector &y); //To add two vector
friend Vector operator-(const Vector &x, const Vector &y); //Subtract x-y
friend Vector operator*(const Vector &x, double c); //c*x
friend Vector operator*(double c, const Vector &x); //x*yy
double& operator[](int i) const { return values[i]; } // eg v[i] = 10
double norm();
double norm2();
double norm(int p);
double infnorm();
int size() const { return length; } // return length of vector
void print(); //prints the vector
void save(char *); //prints the vector in a file
};
•They are not member functions.
•They can access private members (length and values) of Vector.
•They allow flexible operations, e.g., 2.0 * v1 (scalar first) which
cannot be done easily with member functions.
Panchatcharam October 2025 56
friend function
Vector operator+(const Vector &x, const Vector &y) {
// assume same length
Vector result([Link]); // create a vector for result
for(int i=0; i<[Link]; i++) {
[Link][i] = [Link][i] + [Link][i]; // access private 'values'
}
return result;
}
•Even though values is private, the friend function can access it directly.
•If this were not a friend, you would need getter functions for values.
Panchatcharam October 2025 57
friend function
Vector operator*(const Vector &x, double c) {
Vector result([Link]);
for(int i=0; i<[Link]; i++) {
[Link][i] = [Link][i] * c;
}
return result;
}
Vector operator*(double c, const Vector &x) {
return x * c; // reuse the previous operator
}
•Friend functions create a new Vector object for the result.
•The function directly accesses the private values array, so it’s efficient.
•You avoid getters and setters, keeping syntax clean: v3 = v1 + v2;.
Panchatcharam October 2025 58
Getters and Setters Methods
class Student {
private:
string name;
int age;
public: int main() {
// Setter for name
void setName(string n) { Student s;
name = n;
} [Link](“Raja"); // setter
setter
// Setter for age (with validation) [Link](20); // setter
void setAge(int a) { cout << [Link]() << " is " << [Link]()
if(a > 0) age = a; << " years old." << endl; // getter
else cout << "Age must be positive!" << endl;
}
[Link](-5); // invalid, setter prevents it
// Getter for name [Link]=10; // compiler error
string getName() const {
return name;
getter //error: 'std::string Student::name' is private
} within this context
// Getter for age }
int getAge() const {
return age;
}
};
Getters and setters must be used outside class to access
data attributes
Panchatcharam October 2025 59
Point Class
int main()
{ Download the CPP File
Point P1,P2;
[Link](1.0,2.0,3.0); class Point{
private:
[Link](); double x, y, z;
[Link](3.0,4.0,5.0); public:
[Link](); Point(double x=0.0, double y=0.0, double z=0.0);
cout<<[Link](P1,P2)<<endl; void SetPoint(double x, double y, double z);
cout<<[Link](P1)<<endl; Point GetPoint();
cout<<[Link](P2)<<endl; void SetX(double x);
cout<<[Link]()<<endl; void SetY(double y);
cout<<[Link]()<<endl; void SetZ(double z);
Point P3=[Link](P1,P2); double GetX();
[Link](); double GetY();
double GetZ();
//cout<<distance(P1,P2)<<endl; void Print();
cout<<distanceFromOrigin(P1)<<endl; double distance(Point P1, Point P2);
cout<<distanceFromOrigin(P2)<<endl; double distanceFromOrigin(Point P);
Point P4=MidPoint(P1,P2); double distanceFromOrigin();
Print(P4); Point MidPoint(Point P1, Point P2);
const Point operator+(const Point &P) const;
Point P5=P1+P2; };
Print(P5);
return 0;
}
Panchatcharam October 2025 60
Vector Class
class Vector Download the HPP File
{
private: Download the CPP File
int length;
double *values;
public:
Vector(int N=0, double=0); //Constructor
Vector(const Vector&); // copy constructor
~Vector(){ delete [] values; } // destructor is defined inline
Vector& operator=(const Vector&); // overload assignment
void LinSpace(double xl,double xu,int n); //Linspace generates the list of equidistant n points between xl and xu
Vector operator+(const Vector &x); //+ operator overloading
friend Vector operator+(const Vector &x, const Vector &y); //To add two vector
friend Vector operator-(const Vector &x, const Vector &y); //Subtract x-y
friend Vector operator*(const Vector &x, double c); //c*x
friend Vector operator*(double c, const Vector &x); //x*yy
double& operator[](int i) const { return values[i]; } // eg v[i] = 10
double norm();
double norm2();
double norm(int p);
double infnorm();
int size() const { return length; } // return length of vector
void print(); //prints the vector
void save(char *); //prints the vector in a file
};
Panchatcharam October 2025 61
Matrix Class
class Matrix
{ Download the HPP File
private:
double *values; Download the CPP File
int row, col;
public:
Matrix(const Matrix& A);
Matrix(double *val, int r, int c)//Constructor
{
row=r;
col=c;
values=new double[row*col];
for(int i=0;i<r;i++)
for(int j=0;j<c;j++)
values[i*c+j]=val[i*c+j];
}
Matrix(int M=0, int N=0, double x=0);
friend Matrix operator*( Matrix &A, Matrix &B);
friend Matrix operator+( const Matrix &A, const Matrix &B);
friend Matrix operator-( const Matrix &A, const Matrix &B);
friend Matrix operator*(double c, const Matrix &A);
double& operator[](int i) const;
friend Vector operator*(const Matrix &A, Vector &x);
Matrix& operator=(const Matrix& );
~Matrix();//destructor
}
Panchatcharam October 2025 62