[go: up one dir, main page]

0% found this document useful (0 votes)
6 views97 pages

Module 5 Final

Module 5 provides an overview of Object-Oriented Programming (OOP), detailing its features such as encapsulation, abstraction, inheritance, and polymorphism. It explains the concepts of classes, objects, and access specifiers in C++, along with practical examples and the significance of the 'this' pointer. The module emphasizes the advantages of OOP, including code reusability and better data security.

Uploaded by

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

Module 5 Final

Module 5 provides an overview of Object-Oriented Programming (OOP), detailing its features such as encapsulation, abstraction, inheritance, and polymorphism. It explains the concepts of classes, objects, and access specifiers in C++, along with practical examples and the significance of the 'this' pointer. The module emphasizes the advantages of OOP, including code reusability and better data security.

Uploaded by

gigachadmaleme
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 97

Module 5 Overview of Object-Oriented

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.

19/04/2025 Prof.Sudha C - VIT 3


Features of OOP
• Encapsulation
• Abstraction
• Inheritance
• Polymorphism
• Class & Object
• Dynamic Binding
• Message Passing
19/04/2025 Prof.Sudha C - VIT 4
Encapsulation
• Encapsulation is the bundling of data and
methods that operate on the data into a single
unit (class).
• Benefits: Protects data from unauthorized
access, improves code maintainability.
• Example: Using private variables

19/04/2025 Prof.Sudha C - VIT 5


Abstraction

• Hides complex implementation details and only exposes essential


features.
• Benefits: Reduces complexity, increases security.

19/04/2025 Prof.Sudha C - VIT 6


Inheritance
• Mechanism where one class acquires
properties and behaviors of another.
• Types: Single, Multiple (via
interfaces), Multilevel, Hierarchical,
Hybrid.
• Example: A ‘Car’ class inheriting from
a ‘Vehicle’ class.

19/04/2025 Prof.Sudha C - VIT 7


Polymorphism
• Ability of a function, object, or method to take multiple forms.
• Types: Compile-time (Method Overloading), Runtime (Method Overriding).
• Example: A ‘Shape’ class with different implementations of the ‘draw()’
method.

19/04/2025 Prof.Sudha C - VIT 8


Dynamic Binding
• Code execution is determined at runtime rather
than compile-time.
• Example: Calling overridden methods using a
parent class reference.

19/04/2025 Prof.Sudha C - VIT 9


Message Passing
• Objects communicate with each other using method
calls.
• Example: ‘Customer’ object sending a request to the
‘Order’ object.

19/04/2025 Prof.Sudha C - VIT 10


Classes & Objects
• Class: Blueprint for creating objects.
• Object: Instance of a class.
• Example: ‘Person’ class with attributes like
name, age, and methods like walk().

19/04/2025 Prof.Sudha C - VIT 11


Classes & Objects

19/04/2025 Prof.Sudha C - VIT 12


Advantages of OOP

•Code reusability
•Easy maintenance
•Better data security
•Scalable and flexible design
•Real-world modeling

19/04/2025 Prof.Sudha C - VIT 13


Simple C++ Program
#include <iostream> // Header file for input and output operations

using namespace std; // Allows use of standard library without std::


prefix

int main() { // Main function - Entry point of the program


cout << "Hello, World!"; // Output statement
return 0; // Returns 0 indicating successful execution
}

19/04/2025 Prof.Sudha C - VIT 14


19/04/2025 Prof.Sudha C - VIT 16
struct is19/04/2025
a keyword in C for data aggregation class
Prof.Sudhais
C -a
VITnew keyword in C+ for data aggregation
17
Using namespace std;
• using namespace std; is a directive in C++ that
allows the programmer to avoid prefixing standard library
components (like cout, cin, endl, etc.) with std::.
#include <iostream>

int main() {
std::cout << "Hello, World!" << std::endl;
return 0;
}
19/04/2025 Prof.Sudha C - VIT 18
Using namespace std;
#include <iostream>

using namespace std;

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;

cout << "Hello, World!" << endl;


return 0;
}19/04/2025 Prof.Sudha C - VIT 20
Using variable
#include <iostream>
using namespace std;

int main() {
int number;

cout << "Enter an integer: ";


cin >> number;

cout << "You entered " << number;


return 0;
}
19/04/2025 Prof.Sudha C - VIT 21
Class
• A class is an implementation of a type. It is the only way to implement User-defined Data
Type (UDT)
• A class contains data members / attributes
• A class has operations / member functions / methods
• A class defines a namespace
• Thus, classes offer data abstraction / encapsulation of Object Oriented Programming
• Classes are similar to structures that aggregate data logically
• A class is defined by class keyword
• Classes provide access specifiers for members to enforce data hiding that separates
implementation from interface
• private — accessible inside the definition of the class
• public — accessible everywhere
• A class is a blue print for its instances (objects)
19/04/2025 Prof.Sudha C - VIT 22
Object
• An object of a class is an instance created according to its blue print.
• Objects can be automatically, statically, or dynamically created
• A object comprises data members that specify its state
• A object supports member functions that specify its behavior
• Data members of an object can be accesses by ”.” (dot) operator on
the object
• Member functions are invoked by ”.” (dot) operator on the object
• An implicit this pointer holds the address of an object. This serves
the identity of the object in C++
• this pointer is implicitly passed to methods
19/04/2025 Prof.Sudha C - VIT 23
C++ Access Specifiers

An Overview of Public, Private, and Protected


Access in C++
Introduction
• Access specifiers in C++ define the visibility and accessibility of
class members.
• Three main access specifiers:
• - Public
• - Private
• - Protected
Public Access Specifier
- Members are accessible from anywhere (inside or outside the class).
- Typically used for interface methods.

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;
}
};

class Derived : public Base {


public:
void show() {
std::cout << "x = " << x << std::endl; // Allowed (protected in
base)
}
};
int main() {
Derived obj;
obj.setX(20);
obj.show();
// obj.x = 30; // Error: 'x' is protected
return 0;
}
Access Control in Inheritance
• Inheritance modifies access levels of base class members:
• - Public inheritance: Public → Public, Protected → Protected
• - Protected inheritance: Public → Protected, Protected →
Protected
• - Private inheritance: Public → Private, Protected → Private

• Private members are never inherited.


Class
In C++, the(class)
default access specifier depends on whether you are defining a class or a struct:
•Default access specifier is private.
•If no access specifier is mentioned, members are
private by default class Example {
int x; // Private by default
public:
int y; // Explicitly public
Struct (struct) };
•Default access specifier is public.
•If no access specifier is mentioned, members
are public by default
struct Example {
int x; // Public by default
private:
int y; // Explicitly private
};
class Base {
protected:
int x; // Protected variable

public:
void setX(int value) {
x = value;
}
};

class Derived : public Base {


public:
void show() {
std::cout << "x = " << x << std::endl; // Allowed (protected in base)
}
};

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

// Access attributes and set values


myObj.myNum = 15;
myObj.myString = "Some text";

// Print attribute values


cout << myObj.myNum << "\n";
cout << myObj.myString;
19/04/2025 return 0; Prof.Sudha C - VIT 36
// Create a Car class with some attributes
class Car {
public:
string brand;
string model;
int year;
};

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 MyClass { // The class


public: // Access specifier
void myMethod(); // Method/function
declaration
};
// Method/function definition outside the
class
void MyClass::myMethod() { int main() {
cout << "Hello World!"; MyClass myObj; // Create
} an object of MyClass
myObj.myMethod(); // Call the
method
return 0;
19/04/2025 Prof.Sudha C - VIT 39
}
#include <iostream>
using namespace std;

class Car {
public:
int speed(int maxSpeed);
};

int Car::speed(int maxSpeed) {


return 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:

1.Access Current Object: It holds the address of the calling object.


2.Differentiate Between Local and Member Variables: It helps resolve naming
conflicts when member variables have the same name as function parameters.
3.Return Current Object: It allows method chaining by returning the object itself.
4.Applicable Only in Non-Static Member Functions: It does not exist in static
functions since they are not tied to any specific object.
19/04/2025 Prof.Sudha C - VIT 42
19/04/2025 Prof.Sudha C - VIT 43
#include <iostream>
using namespace std;

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
}

19/04/2025 Prof.Sudha C - VIT 46


Bank Account Management System

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.

19/04/2025 Prof.Sudha C - VIT 47


#include <iostream>
using namespace std;

class BankAccount {
private:
int accountNumber;
float balance;

public:
BankAccount(int accNum, float initialBalance) {
accountNumber = accNum;
balance = initialBalance;
}

void deposit(float amount) {


balance += amount;
cout << "Deposit Successful! New Balance: $" << balance << endl;
}

19/04/2025 Prof.Sudha C - VIT 48


void withdraw(float amount) {
if (amount > balance) {
cout << "Insufficient Balance!" << endl;
} else {
balance -= amount;
cout << "Withdrawal Successful! Remaining Balance: $" << balance << endl;
}
}

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;
}

19/04/2025 Prof.Sudha C - VIT 49


Student Information System

Problem Statement:

Create a Student class with the following specifications:


1.Private members:
•name (string)
•rollNumber (integer)
•marks (float)
2.Public methods:
•A constructor to initialize the student’s details
•displayInfo() to print the student's details
•updateMarks(float) to update the marks
Task:
Write a C++ program to create an object of the Student class, update marks, and display the updated
information.
19/04/2025 Prof.Sudha C - VIT 50
#include <iostream> void updateMarks(float newMarks) {
using namespace std; marks = newMarks;
}
class Student {
private: void displayInfo() {
string name; cout << "Student: " << name << " | Roll Number: " <<
int rollNumber; rollNumber << " | Marks: " << marks << "%" << endl;
float marks; }
};
public:
Student(string studentName, int roll, float initialMarks) { int main() {
name = studentName; Student s1("John Doe", 101, 85.5);
rollNumber = roll; s1.displayInfo();
marks = initialMarks; s1.updateMarks(90.0);
} s1.displayInfo();
return 0;
}

19/04/2025 Prof.Sudha C - VIT 51


Shape Hierarchy

Problem Statement:

Design a base class Shape and a derived class Circle.

1.Shape Class:
•Protected member: area (float)
•Public method: displayArea()

2.Circle Class (Inherits from Shape):


•Private member: radius (float)
•Public methods:
•Constructor to initialize radius
•calculateArea() to compute the area (area = 3.14 * radius * radius)
•Override displayArea() to display the circle’s area

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;

class Shape { void calculateArea() {


protected: area = 3.14 * radius * radius;
float area; }

public: void displayArea() {


void displayArea() { cout << "Circle Area: " << area << endl;
cout << "Area: " << area << endl; }
} };
};
int main() {
class Circle : public Shape { Circle c1(5.0);
private: c1.calculateArea();
float radius; c1.displayArea();
return 0;
public: }
Circle(float r) {
radius = r;
}

19/04/2025 Prof.Sudha C - VIT 53


Employee Payroll System

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.

19/04/2025 Prof.Sudha C - VIT 54


#include <iostream> float getSalary() {
using namespace std; return salary;
}
class Employee {
private: void displayEmployee() {
int empId; cout << "Employee ID: " << empId << " | Salary: $" <<
float salary; salary << endl;
}
public: };
Employee(int id, float initialSalary) {
empId = id; int main() {
salary = initialSalary; Employee e1(101, 50000);
} e1.displayEmployee();
e1.setSalary(55000);
void setSalary(float newSalary) { cout << "Updated ";
salary = newSalary; e1.displayEmployee();
} return 0;
}

19/04/2025 Prof.Sudha C - VIT 55


19/04/2025 Prof.Sudha C - VIT 56
Constructors in C++

• Overview, Types, and Examples


Introduction
• A constructor is a special member function of a class
• It is automatically called when an object is created
• Used to initialize objects
• Has the same name as the class and no return type
Constructor Syntax
class ClassName {
public:
ClassName() { /* constructor body */ }
};
main(){
// Example usage:
ClassName obj; // Constructor is called automatically
}
Types of Constructors
1. Default Constructor
2. Parameterized Constructor
3. Copy Constructor
Default Constructor
• A constructor that takes no arguments

class Demo {
public:
Demo() { cout << "Default Constructor"; }
};

Demo obj; // Calls the default constructor


Parameterized Constructor
• A constructor that takes arguments to initialize an object

class Demo {
public:
int x;
Demo(int val) { x = val; }
};

Demo obj(10); // Initializes x with 10


Copy Constructor
• A constructor that initializes an object using another object

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:

1.Avoid infinite recursion (which happens if we pass by value).

2.Improve performance (since no extra copies are made).

3.Ensure safety (const prevents modification of the original object).


Constructor Overloading
• Multiple constructors in the same class with different parameters

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.

19/04/2025 Prof.Sudha C - VIT 72


Declaration of Friend Function
in C++

// Creating a class named class_Name


class class_Name
{
// declartion of class properties
friend return_type function_Name(Argument_1,...,Argument_5);
}

19/04/2025 Prof.Sudha C - VIT 73


#include <iostream>
// Global Function to find the time of Travel not tied to class.
using namespace std;
double findTimeofTravel (Travel t)
{
// Creating a class named Travel.
// Calculate the time of Travel, i.e., distance/speed.
class Travel
// Implicity convert the int data type to double data type.
{
double time = (double)t.distance / (double)t.speed;
private:
return time;
// Make private data members, namely speed and distance.
}
int speed;
int main ()
int distance;
{
// Create an instance of the Travel class.
public:
Travel t;
// A member function to assign the private data member's
values from the user.
// Assign values to the instance t.
void set_values (int a, int b)
t.set_values(10, 30);
{
speed = a;
// Call the global friend function to calculate the time taken for
distance = b;
the Travel.
}
cout << "Time of Travel: " << findTimeofTravel (t) << " hrs" <<
// A global friend function which calculates the time taken for
endl;
the Travel.
return 0;
friend double findTimeofTravel (Travel); // Friend function
}
}; 19/04/2025 Prof.Sudha C - VIT 74
C++ Functions and Static Members
Understanding Static Members, Friend Functions, and Function Features
Static Data Members
- Declaredusing `static` keyword inside a class.
- Shared among all objects of the class.
- Memory allocated once for the entire class.

Static data members are initialized before any object


of the class is created.

**Syntax:** - static data_type data_member_name;

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 MyClass::count = 0; // Initializing the


static member variable
MyClass constructor called
MyClass constructor called
Count = 2
Accessing a Static Member in C++
1. Using a class object:
class A {
public:
static int var;
};

int A::var = 5;

int main() {
A obj;

// Access the static data member using the class object


std::cout << obj.var << std::endl;

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

Feature Static Members Non-Static Members


Class (shared across all Individual objects (separate
Belongs to
objects) for each object)
Exists throughout program Created and destroyed with
Lifetime
execution object lifecycle
ClassName::staticMember
Accessed via object.nonStaticMember
or object.staticMember
Access to this ❌ (No this pointer) ✅ (Has this pointer)
Access to static data ✅ Yes ✅ Yes
❌ No (Because they require
Access to non-static data ✅ Yes
an object)
void show() {
#include <iostream> std::cout << "Non-static variable: " <<
nonStaticVar
class Example { << ", Static variable: " << staticVar <<
public: std::endl;
int nonStaticVar; // Non-static member }
(separate for each object) };
static int staticVar; // Static member
(shared among all objects) // Initialize static variable outside the class
int Example::staticVar = 0;
Example(int val) {
nonStaticVar = val; int main() {
staticVar++; // Incrementing shared Example obj1(10);
variable Example obj2(20);
}
obj1.show();
obj2.show();

Non-static variable: 10, Static variable: 1 return 0;


Non-static variable: 20, Static variable: 2 }

•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:**

inline int add(int a, int b) {


return a + b;
}
Inline Function
• When an instruction of a function call is encountered during the

compilation of a program, its memory address is stored by the

compiler.

• The function arguments are copied on the stack and after the

execution of the code, the control is transferred to the calling

instruction.

• This process can sometimes cause overhead in function calls,

especially if the function is small and its execution time is less than

the switching time.

• This issue is resolved by using the inline functions.


Circumstances Where the Compiler Does Not
Consider Inline Functions
• Inlining a function is not mandatory.

• It should be considered to be just a request, and it’s execution totally


depends on the compiler. The compiler decides whether to accept or
decline the request of inlining the function based on some
circumstances as discussed below:

• The compiler denies the request to make a function an inline function


if it contains a return statement but does not return anything.
• All those functions that contain a loop statement (for loop, while loop,
or do-while loop) can not be considered as an inline function by the
compiler.
• The compiler will not consider a function to be an inline function if it is
recursive.
• If the function contains one or more static variables, the compiler will
deny the request to make it an inline function.
• If the function contains a switch or a go-to statement, the compiler will
deny the suggestion to make it an inline function.
Call by Reference
- Passes arguments as references to modify original variables.
- Used for efficiency and modifying variables.
**Syntax:**
//Declaration
return_type function_name( type_of_argument,type_of_argument,..);
//Calling
function_name(actual_argument,actual_argument,..);

//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:**

void display(int a, int b = 10) {


cout << a << " " << b;
}
display(5); // Output: 5 10
Functions with Default Arguments
#include<iostream>
using namespace std;

// A function with default arguments, it can be called with


// 2 arguments or 3 arguments or 4 arguments.
int sum(int x, int y, int z=0, int w=0)
{
return (x + y + z + w); /* Driver program to test above
function*/
} int main()
{
cout << sum(10, 15) << endl;
cout << sum(10, 15, 25) << endl;
cout << sum(10, 15, 25, 30) << endl;
return 0;
}
Functions with Objects as Arguments
- Pass objects to functions by value or reference.
- Enables operations on class objects.

**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.

You might also like