Module 5 Final
Module 5 Final
Programming
Features of OOP - Classes and Objects - “this” pointer - Constructors and Destructors -
Static Data Members, Static Member Functions and Objects - Inline Functions – Call by
reference - Functions with default Arguments - Functions with Objects as Arguments –
Friend Functions and Friend Classes.
Prof. Sudha C
Assistant Professor
SCOPE – VITCC
19/04/2025 Prof.Sudha C - VIT 1
19/04/2025 Prof.Sudha C - VIT 2
Introduction to OOP
• Object-Oriented Programming (OOP) is a
programming paradigm based on objects and classes.
• It promotes modularity, reusability, and scalability in
software development.
• Used in languages like Java, C++, Python, etc.
•Code reusability
•Easy maintenance
•Better data security
•Scalable and flexible design
•Real-world modeling
int main() {
std::cout << "Hello, World!" << std::endl;
return 0;
}
19/04/2025 Prof.Sudha C - VIT 18
Using namespace std;
#include <iostream>
int main() {
cout << "Hello, World!" << endl;
return 0;
}
19/04/2025 Prof.Sudha C - VIT 19
Using namespace std;
Instead of using using namespace std; globally, it's better to use it selectively:
#include <iostream>
int main() {
using std::cout;
using std::endl;
int main() {
int number;
Example:
class Example {
public:
int x;
void display() { std::cout << x; }
};
class Example {
public:
int x; // Public variable
void display() { // Public function
std::cout << "x = " << x << std::endl;
}
};
int main() {
Example obj;
obj.x = 10; // Allowed (public)
obj.display(); // Allowed (public)
return 0;
}
Private Access Specifier
- Members are accessible only within the class.
- Not accessible from outside or derived classes.
Example:
class Example {
private:
int x;
public:
void setX(int value) { x = value; }
};
class Example {
private:
int x; // Private variable
public:
void setX(int value) { // Public function to modify private data
x = value;
}
void display() {
std::cout << "x = " << x << std::endl;
}
}; int main() {
Example obj;
// obj.x = 10; // Error: 'x' is
private
obj.setX(10); // Allowed via
public method
obj.display();
return 0;
}
Protected Access Specifier
- Similar to private but accessible in derived classes.
- Used for inheritance.
Example:
class Base {
protected:
int x;
};
class Derived : public Base {
void show() {
std::cout << x; }
};
class Base {
protected:
int x; // Protected variable
public:
void setX(int value) {
x = value;
}
};
public:
void setX(int value) {
x = value;
}
};
int main() {
Derived obj;
obj.setX(20);
obj.show();
// obj.x = 30; // Error: 'x' is protected
return 0;
}
Conclusion
• - Access specifiers control member visibility.
• - Use public for interface methods.
• - Use private for encapsulation.
• - Use protected for inheritance control.
class MyClass { // The class
public: // Access specifier
int myNum; // Attribute (int variable)
string myString; // Attribute (string
variable)
};
int main() {
MyClass myObj; // Create an object of MyClass
int main() {
// Create an object of Car
Car carObj1;
carObj1.brand = "BMW";
carObj1.model = "X5";
carObj1.year = 1999;
// Create another object of Car
Car carObj2;
carObj2.brand = "Ford";
carObj2.model = "Mustang";
carObj2.year = 1969;
// Print attribute values
cout << carObj1.brand << " " << carObj1.model << " " << carObj1.year << "\
n";
cout << carObj2.brand << " " << carObj2.model << " " << carObj2.year << "\
19/04/2025 Prof.Sudha C - VIT 37
n";
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;
} 19/04/2025 Prof.Sudha C - VIT 38
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:
class Car {
public:
int speed(int maxSpeed);
};
int main() {
Car myObj; // Create an object of Car
cout << myObj.speed(200); // Call the method with an
argument
return 0;
} 19/04/2025 Prof.Sudha C - VIT 40
“this” pointer
In C++, the this pointer is an implicit pointer available in all non-static member functions
of a class.
It points to the current instance of the class.
Key Features of this Pointer:
class Example {
private:
int x; int main() {
Example obj;
public: obj.setX(10);
void setX(int x) { obj.print();
this->x = x; // Using this pointer to
return 0;
differentiate between member and parameter
} }
void print() {
cout << "Value of x: " << this->x << endl;
}
};
19/04/2025 Prof.Sudha C - VIT 44
#include <iostream>
using namespace std; int main() {
Example obj;
class Example { obj.setX(20).print(); // Method chaining
private: return 0;
int x; }
public:
Example& setX(int x) {
this->x = x;
return *this; // Returning the current object
}
void print() {
cout << "Value of x: " << x << endl;
}
};
19/04/2025 Prof.Sudha C - VIT 45
#include <iostream>
using namespace std; void print() {
cout << "x: " << x << ", y: " << y << endl;
}
class Example { };
private:
int x; int main() {
int y; Example obj;
obj.setX(10).setY(20).print(); // Chaining function calls
public:
Example& setX(int x) { return 0;
this->x = x; }
return *this; // Returning the object reference
}
Example& setY(int y) {
this->y = y;
return *this; // Returning the object reference
}
Problem Statement:
Design a class BankAccount that represents a bank account. The class should have:
1.Private members:
•accountNumber (integer)
•balance (float)
2.Public methods:
•A constructor to initialize accountNumber and balance
•deposit(float amount) to add money to the account
•withdraw(float amount) to subtract money if the balance is sufficient
•displayBalance() to print the current balance
Task:
Write a C++ program to create an object of BankAccount and perform deposit and withdrawal
operations.
class BankAccount {
private:
int accountNumber;
float balance;
public:
BankAccount(int accNum, float initialBalance) {
accountNumber = accNum;
balance = initialBalance;
}
void displayBalance() {
cout << "Account Number: " << accountNumber << " | Balance: $" << balance << endl;
}
};
int main() {
BankAccount acc(101, 5000);
acc.deposit(1500);
acc.withdraw(2000);
acc.displayBalance();
return 0;
}
Problem Statement:
Problem Statement:
1.Shape Class:
•Protected member: area (float)
•Public method: displayArea()
Task:
Write a program that creates a Circle object, calculates its area, and displays it.
19/04/2025 Prof.Sudha C - VIT 52
#include <iostream>
using namespace std;
Problem Statement:
Implement a Employee class for managing payroll.
1.Private members:
•empId (integer)
•salary (float)
2.Public methods:
•Constructor to initialize empId and salary
•setSalary(float) to modify the salary
•getSalary() to fetch the salary
Task:
Write a program to create an employee object, update the salary, and print the updated salary.
class Demo {
public:
Demo() { cout << "Default Constructor"; }
};
class Demo {
public:
int x;
Demo(int val) { x = val; }
};
class Demo {
public:
int x;
Demo(int val) { x = val; }
Demo(const Demo &obj) { x = obj.x; }
};
Demo obj1(10);
Demo obj2(obj1); // Copy constructor is called
#include <iostream> int main() {
using namespace std; Demo obj1(10); // Calls parameterized
constructor
class Demo { Demo obj2 = obj1; // Calls copy constructor
public:
int x; obj1.display();
obj2.display();
// Parameterized Constructor
Demo(int val) { return 0;
x = val; }
cout << "Parameterized Constructor called" <<
endl;
}
// Copy Constructor
Demo(const Demo &obj) {
x = obj.x;
cout << "Copy Constructor called" << endl;
}
Parameterized Constructor called
void display() { Copy Constructor called
cout << "Value of x: " << x << endl; Value of x: 10
} Value of x: 10
};
✅ Use const Demo &obj (Pass by Reference) in the copy constructor to:
class Demo {
public:
Demo() { cout << "Default Constructor"; }
Demo(int x) { cout << "Parameterized Constructor"; }
};
Demo obj1;
Demo obj2(10);
Constructor with Dynamic Memory
• Allocating memory dynamically in constructors
class Demo {
public:
int* ptr;
Demo(int val) {
ptr = new int;
*ptr = val;
}
~Demo() { delete ptr; }
};
Demo obj(20);
Destructors in C++
• Destructor is used to clean up resources
class Demo {
public:
~Demo() { cout << "Destructor called"; }
};
int main() {
Demo obj;
return 0;
}
#include <iostream>
using namespace std; // Destructor: Called when the object is
destroyed.
class Demo { ~Demo() {
public: cout << "Destructor called: Cleaning up
int value; Demo with value " << value << endl;
}
// Constructor: Initializes the 'value' };
member.
Demo(int val) : value(val) { int main() {
cout << "Constructor called: Value is " << // Creating an object of Demo.
value << endl; Demo obj(42);
}
// 'obj' goes out of scope when main() ends,
// and the destructor is automatically
invoked.
return 0;
}
#include <iostream> // Destructor: Releases the dynamically
using namespace std; allocated memory
~Demo() {
class Demo { cout << "Destructor called: Deleting
public: memory with value " << *ptr << endl;
int* ptr; delete ptr;
}
// Constructor: Allocates memory };
dynamically
Demo(int val) { int main() {
ptr = new int; // Creating an object; the constructor is
*ptr = val; called here.
cout << "Constructor called: Memory Demo obj(10);
allocated with value " << *ptr << endl;
} // When main() returns, the object 'obj' goes
out of scope,
// and the destructor is automatically called.
return 0;
}
Point to Note
• Constructors initialize objects automatically
• Three types: Default, Parameterized, and Copy
• Supports overloading
• Used with dynamic memory allocation
• Destructor cleans up resources
Friend Function in C++
• A function can be declared as the friend of a class in C++. This function is called
a friend function for that class.
•A friend function in C++ has the privilege to access all
the private and protected data of members of the class whose friend it has been
declared.
• These functions can be used to access the member functions of a class while still
enforcing data abstraction. Classes can also be declared as a friend of another class.
class Sample {
static int count; // Declaration
};
int Sample::count = 0; // Definition
#include <iostream>
int main() {
MyClass obj1; // First constructor call, count
class MyClass {
becomes 1
public:
MyClass obj2; // Second constructor call,
MyClass() {
count becomes 2
std::cout << "MyClass constructor called" <<
std::endl;
std::cout << "Count = " << MyClass::count <<
count++; // incrementing count inside the
std::endl;
constructor
}
return 0;
}
static int count;
};
int A::var = 5;
int main() {
A obj;
return 0;
}
Accessing a Static Member in C++
2. Using Scope Resolution operator
class A {
public:
static int var; Static data members can be
}; accessed even without
creating an object of the
int A::var = 5; class.
int main() {
// Access the static data member using the scope resolution
operator
std::cout << A::var << std::endl;
return 0;
}
int main()
{
#include <iostream> // creating two objects of
using namespace std; myClass
myClass obj1, obj2;
// creating a class
class myClass{ cout << "Value of var: " <<
public: obj1.var << endl;
static int var;
}; // changing value of var by
using obj2
// initializing obj2.var = 7;
int myClass:: var = 5;
cout << "New value of var: " <<
obj1.var << endl;
Value of var: 5
New value of var: 7 return 0;
}
Static Member Functions
- Declared using `static` keyword.
- Can access only static members.
- Called using class name.
As we can call static member function by just
using class name and function name, they
can be called even if no object of class be
created.
**Syntax:** - Class_name :: function_name()
class Sample {
public:
static void show() {
cout << "Static function called";
};
// initializing static data
#include <iostream>
member
using namespace std;
int myClass:: var = 5;
// creating a class
int main()
class myClass{
{
public:
// calling static member
static int var;
function
// object of this class is not
// defining static function
created yet
static int get_val()
cout << "Print the value of
{
var: " << myClass::get_val() <<
return var;
endl;
}
return 0;
};
}
Key Differences Between Static and Non-Static Members
•nonStaticVar: Each object (obj1 and obj2) has its own copy with different values (10 and 20).
•staticVar: It is shared among all objects, so it gets incremented once per object creation.
Objects and Inline Functions
- Inline functions improve performance by reducing function call
overhead.
- Defined using `inline` keyword before function definition.
**Syntax:**
compiler.
• The function arguments are copied on the stack and after the
instruction.
especially if the function is small and its execution time is less than
//Definition
return_type function_name(type_of_argument &alias_variable,..)
{ ....;
void swap(int &x, int &y) {
} int temp = x;
x = y;
y = temp;
}
// Program to swap two values using
// CALL BY REFERENCE
int main() {
#include <iostream> int a = 10, b = 20;
using namespace std; cout << "\nVALUES BEFORE SWAPPING :\n";
cout << "A:" << a << ",B:" << b;
// function declaration // function calling
void swap(int &, int &); swap(a, b);
cout << "\nVALUES AFTER SWAPPING :\n";
cout << "A:" << a << ",B:" << b;
cout << "\n";
return 0;
}
// function definition
void swap(int &x, int &y) {
int t;
t = x;
x = y;
VALUES BEFORE SWAPPING : y = t;
A:10,B:20 }
VALUES AFTER SWAPPING :
A:20,B:10
Functions with Default Arguments
A default argument is a value provided in a
function declaration that is automatically
assigned by the compiler if the caller of the
function doesn’t provide a value for the argument
with a default value.
Functions with Default Arguments
- Allows omission of parameters with default values.
- Defined using assignment (`=`) in function prototype.
**Syntax:**
**Syntax:**
class Sample {
public:
int data;
void show(Sample obj) {
cout << obj.data;
}
};
#include <iostream> int main() {
using namespace std; // object declarations
Demo d1;
class Demo { Demo d2;
private: Demo d3;
int a;
// assigning values to the data member of
public: objects
void set(int x) { a = x; } d1.set(10);
d2.set(20);
void sum(Demo ob1, Demo ob2) { a = ob1.a
+ ob2.a; } // passing object d1 and d2
d3.sum(d1, d2);
void print() { cout << "Value of A : " << a <<
endl; } // printing the values
}; d1.print();
d2.print();
d3.print();
Value of A : 10 return 0;
Value of A : 20 }
Value of A : 30
Friend Functions
- Not a member of a class but has access to its private members.
- Declared inside class with `friend` keyword.
**Syntax:**
class Sample {
int data;
friend void show(Sample obj);
};
void show(Sample obj) {
cout << obj.data;
}
Friend Classes
- A friend class in C++ is a class that is granted access to the private and protected members of
another class. This is useful when two classes need to closely collaborate but still maintain
encapsulation.
- Declared using `friend class` keyword.
**Syntax:**
class B;
class A {
int data;
friend class B;
};
class B {
void show(A obj) {
cout << obj.data;
}
};
Conclusion
- Static members optimize memory.
- Inline functions improve speed.
- Call by reference enables modification.
- Friend functions and classes allow controlled access.