[go: up one dir, main page]

0% found this document useful (0 votes)
35 views54 pages

OOP Unit 1 Notes

Download as pdf or txt
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 54

1|Page

Unit – I
Fundamentals of Object-Oriented
Programming
1. Introduction to Object-Oriented Programming
Object-Oriented Programming (OOP) is a programming paradigm centered around the concept
of "objects," which are instances of "classes." In OOP, the focus is on using objects to represent
real-world entities, allowing for modular, reusable, and maintainable code.

1.1 Advantages of Object-Oriented Programming over Procedural Programming

1. Modularity through Classes:

 OOP allows you to group related functions and data into classes, promoting modular
design. This makes it easier to organize and manage large codebases compared to PP,
where code can become fragmented.

2. Code Reusability:

 Through the concept of inheritance, OOP allows new classes to inherit properties and
methods from existing classes, reducing code duplication. PP does not have this built-
in mechanism for reusing code.

3. Encapsulation:

 OOP supports encapsulation, which restricts access to an object's internal state through
access control (public, private, and protected members). This provides better control
over how data is accessed and modified. PP doesn't offer such data protection
mechanisms.

4. Abstraction:

 OOP promotes data abstraction, allowing developers to expose only essential features
of an object while hiding the complex implementation details. PP lacks a native way to
provide this level of abstraction, leading to more complex code exposure.

5. Ease of Maintenance and Scalability:


2|Page

 Due to its modular nature and clear separation of concerns, OOP is easier to maintain
and scale. As applications grow, OOP allows incremental development by adding new
objects or modifying existing ones with minimal impact on the rest of the system. PP
can become harder to maintain as the code grows.

6. Polymorphism:

 OOP allows for polymorphism, enabling objects of different types to be treated as


instances of the same class through interfaces or abstract classes. This adds flexibility
to the design and reduces complexity in code logic, something not directly available in
PP.

7. Real-World Modeling:

 OOP better represents real-world entities and their interactions through objects and
classes, making it more intuitive for modeling complex systems. PP doesn’t naturally
align with real-world concepts as easily.

8. Dynamic Binding:

 OOP uses dynamic (or late) binding for methods, allowing the method that is invoked
to be determined at runtime. This supports more flexible and adaptable code. PP
generally relies on static binding, determined at compile time.

1.2 Need of Object-Oriented Programming

 To provide facility of code reusability which is supported by inheritance.

 To provide security of code using access specifiers.

 To bind together the data and the functions that operate on this data, so no other part of

the code can access this data except that function.

 To hide unnecessary details using data abstraction and encapsulation.

 To build complex system by splitting the complexity level by level.

1.2 Fundamentals of Object-Oriented Programming

1. Namespaces
3|Page

In C++, namespaces are used to avoid name conflicts, especially when multiple libraries or
files have classes or functions with the same name.

A namespace allows us to group named entities that would otherwise have global scope.

Example:

namespace CarNamespace {
class Car {
public:
void drive() { cout << "Driving"; }
};
}
int main() {
CarNamespace::Car myCar;
myCar.drive(); // Accessing via namespace
}
2. Objects

Objects are instances of classes in C++. Each object holds data (attributes) and can perform
operations (methods) defined by the class.

Example:

class Car {
public:
string color;
void drive() {
cout << "Car is driving";
}
};
int main() {
Car myCar; // Creating an object
myCar.color = "red"; // Accessing attributes
myCar.drive(); // Calling method
}
4|Page

3. Classes

A class in C++ is a user-defined type that serves as a blueprint for creating objects. It defines
attributes (data members) and behaviors (methods).

Example:

class Car {
public:
string color;
string model;
void drive() {
cout << "The car is driving";
}
};
4. Data Members

Data members are the variables declared inside a class in C++.

They hold the object's state or properties.

Example:

class Car {
public:
string color; // Data member
string model; // Data member
};
5. Methods

Methods (also known as member functions in C++) are functions defined inside a class that
operate on the class's data members.

They define the behavior of objects.

Example:

class Car {
public:
5|Page

void drive() { // Method


cout << "The car is driving";
}
};
6. Messages

In C++, sending a message refers to calling a method of an object.

It is the mechanism by which an object is instructed to perform an action.

Example: In the below example, calling the drive() method on an object is equivalent to
sending a message to the object to perform an action.

Car myCar;
myCar.drive(); // Message to the object to call the drive() method
7. Data Encapsula on

Encapsulation in C++ refers to bundling the data (attributes) and methods (functions) into a
single unit, i.e., a class, and controlling access to them using access specifiers (private,
protected, public).

Example:

class Car {
private:
string color; // Encapsulated data
public:
void setColor(string c) {
color = c; // Accessed via method
}
string getColor() {
return color; // Accessed via method
}
};
8. Data Abstrac on
6|Page

Abstraction in C++ means exposing only the essential details to the user, while hiding the
complex implementation details.

Users interact with the object through its public interface.

Example:

class Car {
private:
string engineStatus;
public:
void start() { // User interacts with this simple method
engineStatus = "running"; // Internal details are hidden
cout << "Car started";
}
};
9. Inheritance

Inheritance in C++ allows a class (derived class) to inherit properties and methods from another
class (base class).

It enables code reuse and the creation of hierarchical relationships.

Example:

class Vehicle {
public:
void start() {
cout << "Vehicle started";
}
};
class Car : public Vehicle { // Inherits from Vehicle
public:
void drive() {
cout << "Car is driving";
}
7|Page

};
int main() {
Car myCar;
myCar.start(); // Inherited method
myCar.drive(); // Car method
}
10. Polymorphism

Polymorphism in C++ allows objects of different classes to be treated as objects of a common


superclass.

It mainly occurs through function overriding and function overloading.

Example:

class Vehicle {
public:
virtual void start() { // Virtual function
cout << "Vehicle starting";
}
};
class Car : public Vehicle {
public:
void start() override { // Overriding method
cout << "Car starting";
}
};
int main() {
Vehicle* v = new Car(); // Polymorphism: Vehicle pointer to a
Car object
v->start(); // Calls Car's start() method
}
1.3 Function Overloading and Overriding
8|Page

Function overloading is a feature in C++ where multiple functions can have the same name
but differ in the type or number of their parameters. The correct function is selected by the
compiler based on the number and types of arguments provided during the function call.

Key Points:

 The function name is the same, but the parameter list must be different (either by type
or by the number of parameters).

 Return type alone is not sufficient for function overloading.

 Function overloading is an example of compile-time polymorphism (also called static


polymorphism).

Example of Function Overloading:

#include <iostream>
using namespace std;

// Function to add two integers


int add(int a, int b) {
return a + b;
}

// Overloaded function to add two floats


float add(float a, float b) {
return a + b;
}

// Overloaded function to add three integers


int add(int a, int b, int c) {
return a + b + c;
}

int main() {
// Calling the overloaded functions
9|Page

cout << "Sum of 2 integers: " << add(10, 20) << endl; //
Calls add(int, int)
cout << "Sum of 2 floats: " << add(1.5f, 2.5f) << endl; //
Calls add(float, float)
cout << "Sum of 3 integers: " << add(10, 20, 30) << endl; //
Calls add(int, int, int)

return 0;
}
2. Function Overriding:

Definition: Function overriding occurs when a derived class provides a specific


implementation of a function that is already defined in its base class. The function in the derived
class "overrides" the function in the base class.

Key Points:

 Function overriding is used in inheritance.

 The function signature (name, return type, and parameters) must be exactly the same
in both the base class and the derived class.

 Function overriding enables runtime polymorphism (dynamic polymorphism) and is


achieved using a virtual function in the base class.

 The overridden function is called based on the type of the object during runtime, not
during compile time.

Example of Function Overriding:

#include <iostream>
using namespace std;

// Base class
class Animal {
public:
// Virtual function
virtual void sound() {
10 | P a g e

cout << "Animal makes a sound" << endl;


}
};

// Derived class
class Dog : public Animal {
public:
// Overriding the sound function in the derived class
void sound() override {
cout << "Dog barks" << endl;
}
};

// Derived class
class Cat : public Animal {
public:
// Overriding the sound function in the derived class
void sound() override {
cout << "Cat meows" << endl;
}
};

int main() {
Animal* animalPtr; // Pointer of type base class
Dog dog;
Cat cat;

// Assign dog object to animalPtr


animalPtr = &dog;
animalPtr->sound(); // Calls the overridden function in Dog class

// Assign cat object to animalPtr


11 | P a g e

animalPtr = &cat;
animalPtr->sound(); // Calls the overridden function in Cat class

return 0;
}
Aspect Function Overloading Function Overriding
Purpose Allows multiple functions with the Allows a derived class to provide a
same name but different specific implementation of a base
parameters. class function.
When it Compile-time (static Runtime (dynamic polymorphism).
occurs polymorphism).
Involves No Yes
inheritance
Function Functions must have different Functions must have the same
signature parameter lists. parameter list and return type.
Keyword No special keyword. virtual keyword in base class, and
used override (optional) in derived class.

1.4 Benefits of Object-Oriented Programming

Modularity: OOP allows you to break down complex problems into smaller pieces by using
classes and objects. Each class can represent a specific part of the problem, making the code
easier to understand, develop, and maintain.

Reusability: Classes can be reused across different parts of a program or even in different
programs. This reduces duplication of code and allows for quicker development since existing
code can be used rather than rewritten.

Encapsulation: OOP allows you to hide the internal workings of objects and show only what
is necessary. This means the implementation details are hidden from the outside world, and
changes to the internal code won’t affect other parts of the program as long as the interface
remains the same.

Inheritance: Inheritance lets you create new classes based on existing ones. This promotes
code reuse and the creation of a hierarchical relationship between classes, where common
functionality is shared.
12 | P a g e

Security: OOP enhances security through encapsulation, which allows you to control access
to the data and methods within an object. By using access modifiers like private, protected, and
public, you can restrict or expose certain parts of your code, ensuring that sensitive data is
protected and only accessible where it's intended to be. This helps prevent unauthorized access
and unintended modifications.

1.5 Comparison between Procedural Programming and Object-Oriented


Programming

Sr. No. Procedural Programming Object-Oriented Programming


1 Program is made up of procedures, Program is made up of classes. Classes
i.e., functions which perform their hold data and code that operate data.
independent tasks.
2 It uses top-down approach for It uses bottom-up approach for program
program design. design.
3 Doesn’t provide features like Provides features like polymorphism,
polymorphism, inheritance, etc. inheritance, etc.
4 No access modes or access control for Multiple levels of access modes or access
data & code, so almost no security for controls for data & code, so data and code
different parts of code. are secured from direct access.
5 Data can flow freely from one part of Data is bound within class.
code to another.
6 Implementation is simple. Implementation is complex.
7 Ex. C, FORTRAN, COBOL C++, JAVA

1.6 Comparison between Data Abstraction and Data Encapsulation

Sr. No. Data Abstraction Data Encapsulation


1 It is the process of binding data It is the process of eliminating
members of a class to the member unimportant details of a class.
functions of that class.
2 Data encapsulation depends on the Data abstraction does not depend on the
data type of object. data type of object.
13 | P a g e

3 It is used in software implementation It is used in software design phase.


phase.
4 Data encapsulation can be achieved by Data abstraction is represented by using
inheritance. abstract classes.

2. C++ Programming
There are four sections in the structure of a C++ program.

1. Include file section


2. Class declaration section
3. Function definition section
4. Main function definition

A sample C++ program is as follows:

#include <iostream>
using namespace std;
int main()
{
cout<<”Hello World\n”;
}
2.1 Data Types

In C++, data types define the type of data that a variable can hold. They specify the size and
type of information associated with variables. C++ has a wide variety of data types that can be
grouped into primitive (built-in) and user-defined types. These allow programmers to store
and manipulate different kinds of data efficiently.

a. Integer Types: Used to store whole numbers (both positive and negative).

 int: Stores 4 bytes of data (typically 32 bits).

int age = 25;

 short: Stores smaller integer values (usually 2 bytes, 16 bits).

short smallNumber = 32000;


14 | P a g e

 long: Used for larger integers (usually 4 or 8 bytes depending on the system).

long largeNumber = 1000000;

 long long: For very large integers, typically 8 bytes.

long long veryLargeNumber = 1000000000000;

b. Floating Point Types: Used to represent numbers with fractional (decimal) values.

 float: Single-precision floating point (typically 4 bytes, 7 decimal places).

float pi = 3.14f;

 double: Double-precision floating point (typically 8 bytes, 15 decimal places).

double bigPi = 3.14159265358979;

 long double: Extended-precision floating point for even more precision (usually 10,
12, or 16 bytes).

c. Character Type

 char: Represents a single character (stored in 1 byte, or 8 bits). It can hold characters
or small integer values (ASCII).

char letter = 'A';

d. Boolean Type

 bool: Represents truth values, either true (1) or false (0).

bool isValid = true;

e. Void Type

 void: Indicates "no type." Used for functions that don't return a value or for generic
pointers. You cannot declare a variable of type void.

void myFunction() {

// No return value

2.2 Structures
15 | P a g e

In C++, a structure (or struct) is a user-defined data type that allows you to group together
variables of different types under a single name. This helps in organizing data and represents a
more complex entity.

Syntax of a Structure

struct StructureName {
// Members (variables)
data_type member1;
data_type member2;
// ...
};
Example:

#include <iostream>
using namespace std;
struct Person {
string name; // Member to store the name
int age; // Member to store the age
float height; // Member to store the height
};
int main() {
// Creating a structure variable
Person person1;
// Assigning values to members
person1.name = "John";
person1.age = 30;
person1.height = 5.9;
// Accessing and printing structure members
cout << "Name: " << person1.name << endl;
cout << "Age: " << person1.age << endl;
cout << "Height: " << person1.height << endl;
return 0;
}
16 | P a g e

 struct Person: Defines a structure named Person with three members—name, age,
and height.
 Accessing Members: Once an instance of the structure (person1) is created, you can
access its members using the dot operator (.), e.g., person1.name.

2.2 Enumerations

In C++, an enumeration (or enum) is a user-defined data type that consists of a set of named
integer constants. It allows you to assign meaningful names to integral constants, making your
code more readable and easier to manage.

Syntax of an Enumeration

enum EnumName {
constant1,
constant2,
constant3,
// ...
};
Example:

#include <iostream>
using namespace std;
enum Day { Monday, Tuesday, Wednesday, Thursday, Friday, Saturday,
Sunday };
int main() {
Day today = Wednesday;
if (today == Wednesday) {
cout << "Today is Wednesday!" << endl;
}
return 0;
}
 enum Day: Defines an enumeration named Day with the values Monday, Tuesday,
Wednesday, etc. By default, the first constant is assigned the value 0, and the
subsequent constants get incremented values (Monday = 0, Tuesday = 1, and so
on).
17 | P a g e

 Using Day: In the main() function, a variable today is created with the enumerated
type Day. It is then assigned the value Wednesday (which corresponds to 2).

Custom Integer Values

You can also explicitly assign integer values to the constants.

enum Day { Monday = 1, Tuesday, Wednesday, Thursday = 10, Friday,


Saturday, Sunday };

 In this case:

o Monday is assigned 1.

o Tuesday and Wednesday automatically get the next values (2, 3).

o Thursday is explicitly set to 10, and Friday, Saturday, and Sunday get the
values 11, 12, and 13.

2.3 Control Structures

In C++, control structures determine the flow of program execution. They allow developers
to control the order in which statements are executed based on conditions and loops. Control
structures are divided into three categories: sequential, selection, and repetition.

1. Sequen al Control Structure

In this structure, the statements are executed one after the other in the order in which they
appear.

2. Selec on (Condi onal) Control Structures

These structures allow decision-making in the program by choosing which block of code to
execute based on a condition. The most common conditional structures are:

a. if Statement

The if statement executes a block of code if a condition is true.

if (condition) {
// Code to execute if condition is true
}
18 | P a g e

Example:

int age = 18;


if (age >= 18) {
cout << "You are eligible to vote." << endl;
}
b. if-else Statement

The if-else statement provides an alternative path if the condition is false.

if (condition) {
// Code if condition is true
} else {
// Code if condition is false
}
Example:
int age = 16;
if (age >= 18) {
cout << "You are eligible to vote." << endl;
} else {
cout << "You are not eligible to vote." << endl;
}
c. else if Ladder: Allows checking multiple conditions.

if (condition1) {
// Code if condition1 is true
} else if (condition2) {
// Code if condition2 is true
} else {
// Code if none of the conditions are true
}
Example:

int score = 85;


if (score >= 90) {
19 | P a g e

cout << "Grade A";


} else if (score >= 80) {
cout << "Grade B";
} else {
cout << "Grade C";
}
d. switch Statement: The switch statement is used for selecting one of many code blocks
to be executed, based on the value of an expression.

switch (expression) {
case constant1:
// Code for constant1
break;
case constant2:
// Code for constant2
break;
default:
// Code if none of the cases match
}
Example:

char grade = 'B';


switch (grade) {
case 'A':
cout << "Excellent!";
break;
case 'B':
cout << "Good!";
break;
default:
cout << "Grade not recognized.";
}

3. Repe on (Looping) Control Structures


20 | P a g e

Loops allow you to repeat a block of code multiple times. The most common loops are:

a. for Loop: Used when the number of iterations is known in advance.

for (initialization; condition; increment) {


// Code to execute
}
Example:

for (int i = 0; i < 5; i++) {


cout << i << " ";
}
b. while Loop: Executes a block of code as long as a condition is true.

while (condition) {
// Code to execute
}
Example:

int i = 0;
while (i < 5) {
cout << i << " ";
i++;
}
c. do-while Loop: Similar to the while loop, but the condition is checked after the loop body
is executed, so it always runs at least once.

do {
// Code to execute
} while (condition);
Example:

int i = 0;
do {
cout << i << " ";
i++;
21 | P a g e

} while (i < 5);

4. Jump Statements: These statements transfer control to other parts of the program.

a. break Statement: Used to exit a loop or switch statement prematurely.

for (int i = 0; i < 10; i++) {


if (i == 5) {
break; // Exits the loop when i is 5
}
cout << i << " ";
}
b. continue Statement: Skips the current iteration of a loop and moves to the next iteration.

for (int i = 0; i < 10; i++) {


if (i == 5) {
continue; // Skips the current iteration when i is 5
}
cout << i << " ";
}
c. return Statement: Exits a function and optionally returns a value.

int add(int a, int b) {


return a + b; // Returns the result of a + b
}
2.4 Arrays

An array in C++ is a collection of elements of the same data type stored in contiguous
memory locations. Arrays allow you to store multiple values under a single name and access
them using an index.

Declaring and Initializing an Array

data_type array_name[size];

 data_type: Type of the array elements (e.g., int, float, char).


 array_name: Name of the array.
 size: Number of elements in the array.
22 | P a g e

Example of Array Declaration and Initialization

int numbers[5] = {10, 20, 30, 40, 50};

Accessing Array Elements: Array elements are accessed using an index, starting from 0.

cout << numbers[0]; // Outputs 10

cout << numbers[4]; // Outputs 50

Modifying Array Elements: You can modify array elements by directly assigning a new value.

numbers[1] = 25; // Changes the second element to 25

Example Program Using Arrays:


#include <iostream>
using namespace std;
int main() {
int numbers[3] = {10, 20, 30};

for (int i = 0; i < 3; i++) {


cout << "Element " << i << ": " << numbers[i] << endl;
}

return 0;
}
2.5 Strings

A string is a sequence of characters. C++ provides multiple ways to work with strings, either
through character arrays or the string class from the Standard Library.

1. Character Arrays

In C++, a string can be represented as an array of characters.

Declaring and Initializing a Character Array

char str[] = "Hello";

Accessing and Modifying Characters


23 | P a g e

Just like arrays, you can access or modify individual characters using the index.

cout << str[0]; // Outputs 'H'


str[1] = 'a'; // Modifies the second character to 'a'
2. C++ string Class

The string class in C++ (from the <string> library) provides more functionality and is easier
to use than character arrays. It allows dynamic size handling and various built-in functions for
string manipulation.

Declaring and Initializing a String

#include <string>
string str = "Hello, World!";
Common String Operations

 Concatenation: You can concatenate two strings using the + operator.

string s1 = "Hello, ";


string s2 = "World!";
string result = s1 + s2; // "Hello, World!"

 Accessing Characters: You can access characters using indexing.

cout << str[0]; // Outputs 'H'

 String Length: Use the .length() or .size() function to get the number of
characters in the string.

cout << str.length(); // Outputs the length of the string

Example Program Using string


#include <iostream>
#include <string>
using namespace std;
int main() {
string name = "Alice";
cout << "Name: " << name << endl;
24 | P a g e

// String concatenation
string greeting = "Hello, " + name;
cout << greeting << endl;

// Getting string length


cout << "Length: " << greeting.length() << endl;
return 0;
}
2.6 Class

In C++, a class is a fundamental concept in Object-Oriented Programming (OOP) that serves


as a blueprint for creating objects. A class encapsulates data and methods that operate on that
data into a single unit. It allows you to model real-world entities and behaviors more naturally
and efficiently.

Defining a Class

A class is defined using the class keyword followed by the class name and a block containing
the class members.

Syntax

class ClassName {
public:
// Public members (accessible from outside the class)
data_type member_variable;
void member_function() {
// Function implementation
}

private:
// Private members (only accessible within the class)
data_type private_variable;
void private_function() {
// Function implementation
25 | P a g e

protected:
// Protected members (accessible within the class and derived
classes)
data_type protected_variable;
void protected_function() {
// Function implementation
}
};
Components of a Class

1. Member Variables (Attributes)

o Variables that hold the data for an object.

o They can be public, private, or protected.

2. Member Functions (Methods)

o Functions that operate on the data or perform actions related to the object.

o They can be public, private, or protected.

3. Access Specifiers

o public: Members are accessible from outside the class.

o private: Members are only accessible within the class itself.

o protected: Members are accessible within the class and by derived classes.

Example of a Class

#include <iostream>
using namespace std;
class Car {
public:
// Constructor
Car(string model, int year) : model(model), year(year) {}
26 | P a g e

// Public method
void displayInfo() {
cout << "Model: " << model << ", Year: " << year << endl;
}
// Public method
void setModel(string m) {
model = m;
}
// Public method
string getModel() {
return model;
}
private:
// Private member variables
string model;
int year;
};
int main() {
// Create an object of the Car class
Car myCar("Toyota Camry", 2022);
// Access public methods
myCar.displayInfo();
// Modify and access the model
myCar.setModel("Honda Accord");
cout << "Updated Model: " << myCar.getModel() << endl;
return 0;
}
2.7 Object

In C++, an object is an instance of a class. When you create an object, you are creating a
specific realization of the class blueprint, which includes both data (attributes) and functions
(methods) defined in the class.
27 | P a g e

Creating and Using Objects

Declaration and Instantiation: To create an object, you first need to define a class and then
instantiate objects of that class.

Syntax

ClassName objectName; // Declaration and instantiation

Member Functions and Object Interaction: Member functions are functions defined within
a class that operate on the class’s data. You can call these functions using the object.

Object Access: You can access and modify the data members and member functions of an
object using the dot operator (.).

Example

#include <iostream>
using namespace std;
class Car {
public:
// Public member variables
string model;
int year;
// Public member function
void displayInfo() {
cout << "Model: " << model << ", Year: " << year << endl;
}
};
int main() {
// Create an object of the Car class
Car myCar;
// Set object attributes
myCar.model = "Toyota Camry";
myCar.year = 2022;
// Call member function
28 | P a g e

myCar.displayInfo(); // Outputs: Model: Toyota Camry, Year: 2022


return 0;

2.8 Class and Data Abstraction

In C++, data abstraction is a core concept of Object-Oriented Programming (OOP) that allows
you to hide the complex implementation details of a class and expose only the necessary
features. This is achieved through the use of classes, which encapsulate data and methods.

1. Encapsulation of Data and Methods: A class encapsulates data (attributes) and methods
(functions) into a single unit. This means that the internal details of how data is managed are
hidden from the outside world.

Example:

class Account {
private:
double balance; // Private data member
public:
// Public methods to access and modify balance
void deposit(double amount) {
if (amount > 0) balance += amount;
}
void withdraw(double amount) {
if (amount > 0 && amount <= balance) balance -= amount;
}
double getBalance() const {
return balance;
}
};
 Here, balance is a private member and cannot be accessed directly from outside the
class. Methods like deposit, withdraw, and getBalance provide controlled access to
balance.
29 | P a g e

2. Hiding Implementation Details: The internal workings of the class, such as how data is
stored or manipulated, are hidden from the user. The user interacts with the class only through
its public interface.

3. Providing a Clear Interface: A class defines a clear and consistent interface for interacting
with its objects. This simplifies the use of complex functionality and makes it easier to maintain
and modify the implementation.

4. Reducing Complexity: By abstracting away the implementation details, classes reduce the
complexity of code. Users interact with objects through well-defined methods, making it easier
to understand and use the functionality provided by the class.

2.9 Access Specifiers

In C++, access specifiers control the accessibility of class members (attributes and methods)
from outside the class. They determine how and where class members can be accessed or
modified. The three primary access specifiers are public, private, and protected.

1. Public

 Members declared as public are accessible from anywhere in the program.

 This means any code that has access to the object of the class can use these members.

2. Private

 Members declared as private are only accessible from within the same class.

 Private members cannot be accessed or modified directly from outside the class. This
provides a way to hide the internal state and only expose necessary functionality
through public methods.

3. Protected

 Members declared as protected are accessible within the same class and by derived
(sub)classes.

 Protected members are not accessible from outside the class unless through a derived
class. This is useful for inheritance when you want to allow derived classes to access or
modify inherited members but keep them hidden from the outside world.

Access Specifier Order


30 | P a g e

Access specifiers can be used in different orders within a class definition:

 Default Access Specifier: In classes, members are private by default if no access


specifier is provided. In structs, members are public by default.

 Multiple Specifiers: You can switch between different access specifiers multiple times
within a class.

Example

#include <iostream>
using namespace std;
class MyClass {
public:
int publicVar; // Public member
void show() {
cout << "Public: " << publicVar << endl;
cout << "Private: " << privateVar << endl; // Accessible
within the class
cout << "Protected: " << protectedVar << endl; // Accessible
within the class
}
private:
int privateVar = 1; // Private member
protected:
int protectedVar = 2; // Protected member
};
int main() {
MyClass obj;
obj.publicVar = 10;
obj.show(); // Displays public, private, and protected vars
return 0;
}

Access Mode Within class Outside of class Derived class


31 | P a g e

Private Accessible Not accessible Not accessible


Protected Accessible Not accessible Accessible
Public Accessible Accessible Accessible

2.10 Separating Interface from Implementation

Interface: The interface of a class defines what the class does. It includes the class's public
members—methods and attributes that are accessible to users of the class. The interface is
typically declared in a header file (.h or .hpp file).

Implementation: The implementation of a class defines how the class performs its tasks. It
includes the definitions of the methods declared in the interface. The implementation is usually
provided in a source file (.cpp file).

For example,

Header File (MyClass.h): Declares the MyClass class and its public interface,
including the constructor and the display() method. This file is included where the
class is used.

Source File (MyClass.cpp): Defines how the methods of MyClass work. This file
includes the header file to ensure that the implementation matches the interface.

Main File (main.cpp): Uses the MyClass class through its interface. It doesn’t need to
know how the class is implemented, only how to use it.

3. Functions

Object-Oriented Programming (OOP) is a programming paradigm centered around the concept


of "objects," which are instances of "classes." In OOP, the focus is on using objects to represent
real-world entities, allowing for modular, reusable, and maintainable code.

3.1 Function Prototype

A function prototype tells the compiler about a function name and how to call the function. The
actual body of the function can be defined the separately.

The function prototype serves the following purposes:

1. It tells the return type of the data that the function will return.
32 | P a g e

2. It tells the number of arguments passed to the function.


3. It tells the data types of the each of the passed arguments.
4. Also it tells the order in which the arguments are passed to the function.

Syntax of a Function Prototype

return_type function_name(parameter_list);

 return_type: The type of value the function returns (e.g., int, void, float, etc.).

 function_name: The name of the function.

 parameter_list: A list of the types (and optionally names) of parameters that the
function takes.

Example of a Function Prototype

int add(int, int); // Function prototype

 int is the return type.

 add is the function name.

 The function takes two parameters of type int.

3.2 Accessing a function

When we talk about "accessing a function", it generally refers to invoking or calling a


function in C++. If the function is part of a class, it can be accessed through an object of that
class.

When we talk about "accessing a function", it generally refers to invoking or calling a


function in C++. If the function is part of a class, it can be called (accessed) through an object
of that class.

There are different types of functions you can access or call in C++:

 Member Functions: Functions that are part of a class.

 Static Member Functions: Class-specific functions that can be called without an


instance of the class.

 Global Functions: Functions that are not part of any class.

Example:
33 | P a g e

class MyClass {
public:
// Member function
void greet() {
cout << "Hello, World!" << endl;
}
};
int main() {
MyClass obj; // Create an object of MyClass
obj.greet(); // Access the greet() function using the object
return 0;
}

The function greet() is a member function of MyClass.

It is accessed in the main() function through the object obj using obj.greet().

3.3 Utility function

A utility function is a helper function that performs a task or provides some functionality, but
it is not tied specifically to manipulating or accessing the internal data of a class. Utility
functions are designed to support other functions, perform calculations, or provide
supplementary features. They can be member functions or non-member functions.

Key Characteristics:

 Perform a supporting task (e.g., calculations, formatting, printing, etc.).

 Not primarily responsible for accessing or modifying class data.

 Can be part of a class or exist outside the class.

 May operate on the class's data, but their primary purpose is to provide utility, rather
than directly interact with member variables.

Example:

// Utility function to calculate square


34 | P a g e

int square(int num) {

return num * num;

int main() {

int number = 4;

cout << "Square of " << number << " is: " << square(number) <<
endl; // Calling utility function

return 0;

3.4 Constructors

A constructor is a special function in a class that is automatically called when an object of that
class is created. The purpose of a constructor is to initialize the object's data members.

Key Characteristics:

 It has the same name as the class.

 No return type, not even void.

 It is called automatically when an object is instantiated.

 Multiple constructors can be defined in a class (this is called constructor overloading).

Types of Constructors:

1. Default Constructor

A default constructor is a constructor that takes no parameters and is used to initialize objects
with default values.

Characteristics:

 No parameters.
35 | P a g e

 If you don't define any constructor, the compiler provides a default constructor
automatically.

Example:

#include <iostream>
using namespace std;
class MyClass {
public:
int data;
// Default constructor
MyClass() {
data = 0; // Initializing with default value
cout << "Default constructor called. Data = " << data << endl;
}
};
int main() {
MyClass obj; // Calls the default constructor
return 0;
}
2. Parameterized Constructor

A parameterized constructor is a constructor that takes parameters to initialize an object with


specific values at the time of creation.

Characteristics:

 Takes one or more parameters.

 Allows you to assign custom values to data members when an object is created.

Example:

#include <iostream>
using namespace std;

class MyClass {
36 | P a g e

public:
int data;

// Parameterized constructor
MyClass(int value) {
data = value; // Initializing with a specific value
cout << "Parameterized constructor called. Data = " << data
<< endl;
}
};

int main() {
MyClass obj(10); // Calls the parameterized constructor with a
value
return 0;
}
3. Copy Constructor

A copy constructor creates a new object by copying the data from an existing object. It is used
when:

 An object is passed by value to a function.

 An object is returned by value from a function.

 You explicitly copy an object.

Characteristics:

 Takes a reference to an object of the same class as its parameter.

 The compiler provides a default copy constructor if you don't define one.

Example:

#include <iostream>
using namespace std;
class MyClass {
public:
37 | P a g e

int data;
// Parameterized constructor
MyClass(int value) {
data = value;
cout << "Parameterized constructor called. Data = " << data
<< endl;
}
// Copy constructor
MyClass(const MyClass &obj) {
data = obj.data; // Copy the value from the existing object
cout << "Copy constructor called. Data = " << data << endl;
}
};
int main() {
MyClass obj1(10); // Calls the parameterized constructor
MyClass obj2 = obj1; // Calls the copy constructor
return 0;
}
3.5 Destructor

A destructor is a special member function that is called automatically when an object goes out
of scope or is explicitly deleted. Its primary purpose is to clean up resources (like memory or
file handles) that the object may have acquired during its lifetime.

Key Characteristics:

 The destructor's name is the same as the class, but with a tilde (~) before it.

 No return type, not even void.

 It takes no arguments (cannot be overloaded).

 It is called automatically when the object is destroyed (e.g., when it goes out of scope
or is deleted).

Example:

#include <iostream>
38 | P a g e

using namespace std;


class MyClass {
public:
// Constructor
MyClass() {
cout << "Constructor called." << endl;
}
// Destructor
~MyClass() {
cout << "Destructor called." << endl;
}
};
int main() {
MyClass obj; // Constructor is called here
// Destructor will be called when obj goes out of scope
return 0;
}
Aspect Constructor Destructor
Purpose Initialize the object's data Clean up resources (memory, files, etc.)
members. when the object is destroyed.
Name Same as the class name. Same as the class name, but with a tilde
(~) prefix.
Return Type No return type, not even void. No return type, not even void.
Parameters Can take parameters (in Takes no parameters (cannot be
parameterized constructors). overloaded).
When Called Automatically when an object is Automatically when an object is
created. destroyed or goes out of scope.

3.6 Objects and Memory Requirements

Types of Memory Allocation

C++ allows two main types of memory allocation for objects:

1. Static (Stack) Allocation


39 | P a g e

2. Dynamic (Heap) Allocation

1. Static Allocation (Stack Memory)

When you create an object in the function's local scope (e.g., in main()), the object is created
on the stack. Stack memory is automatically managed, and the object is destroyed when it goes
out of scope.

Example:

class MyClass {
public:
int a;
MyClass() { cout << "Object created on the stack." << endl; }
~MyClass() { cout << "Object destroyed." << endl; }
};

int main() {
MyClass obj; // Static allocation (on the stack)
return 0; // Object is destroyed automatically at the end of
the function
}
In this case, the object obj is allocated on the stack and is automatically destroyed when the
function ends.

2. Dynamic Allocation (Heap Memory)

When you allocate an object dynamically using the new keyword, it is created on the heap,
which is a larger pool of memory. You need to manually manage the memory and delete the
object when it is no longer needed.

Example:

class MyClass {
public:
int a;
MyClass() { cout << "Object created on the heap." << endl; }
~MyClass() { cout << "Object destroyed." << endl; }
40 | P a g e

};

int main() {
MyClass* obj = new MyClass(); // Dynamic allocation (on the heap)
delete obj; // Manually deallocating the object
return 0;
}
In this case, the object is allocated on the heap, and you need to call delete to free the memory
when you're done using the object.

3.7 Static Members: variable and functions

In C++, static members (both variables and functions) are associated with the class rather than
with any individual object of the class. This means that static variables and static functions
are shared across all instances of the class.

1. Static Member Variables

A static member variable is a class-level variable that is shared by all objects of the class. It
is declared using the static keyword and is initialized outside the class definition.

Key Characteristics:

 Shared by all objects of the class.

 Retains its value between function calls.

 Can be accessed using the class name or an object of the class.

 Must be defined (and optionally initialized) outside the class.

Example:

#include <iostream>
using namespace std;

class MyClass {
public:
static int count; // Static variable declaration
41 | P a g e

MyClass() {
count++; // Increment static variable for each object created
}
};

// Definition and initialization of static variable


int MyClass::count = 0;

int main() {
MyClass obj1, obj2, obj3; // Creating multiple objects

cout << "Total objects created: " << MyClass::count << endl; //
Access static variable
return 0;
}
 count is a static variable shared by all objects.
 Each time an object (obj1, obj2, obj3) is created, the constructor increments the static
variable count.
 The total number of objects created is printed using MyClass::count.
2. Static Member Functions

A static member function is a function that belongs to the class, not to any specific object. It
can access only static member variables and other static member functions. It cannot access
non-static members because it is not tied to any particular object.

Key Characteristics:

 Can only access static variables and other static functions.

 Can be called without creating an object.

 Called using the class name or through an object, but calling through the class name is
more common.

Example:
42 | P a g e

#include <iostream>
using namespace std;

class MyClass {
public:
static int count; // Static variable

MyClass() {
count++;
}

// Static member function


static void showCount() {
cout << "Total objects created: " << count << endl;
}
};

// Definition of static variable


int MyClass::count = 0;

int main() {
MyClass obj1, obj2; // Creating objects

// Call static function using the class name


MyClass::showCount(); // Output: Total objects created: 2

return 0;
}
 showCount() is a static member function that can be called without creating an object.

 It can only access the static variable count and prints the total number of objects created.

 In this case, MyClass::showCount() is used to call the static function.


43 | P a g e

Key Differences Between Static and Non-Static Members

Aspect Static Members Non-Static members


Access Can be accessed using the class Accessed using an object of the
name. class.

Scope Shared by all objects of the class. Unique to each object.

Memory Allocated once, shared across all Memory allocated for each object
objects. separately.

Lifetime Exists for the lifetime of the Exists for the lifetime of the object.
program.

Functions Can access only static data Can access both static and non-static
members. members.

3.8 Inline Function

In C++, an inline function is a function that is expanded in line when it is invoked, rather than
being called in the traditional way. This means that, instead of jumping to the function's
definition and returning back to the calling function, the code of the inline function is directly
substituted at the point of the call.

The main purpose of an inline function is to optimize performance by avoiding the overhead
of a function call, particularly for small, frequently called functions.

Syntax of Inline Function

You can define a function as inline by prefixing the function definition with the keyword
inline.

inline return_type function_name(parameters) {


// Function body
}
Example:

#include <iostream>
using namespace std;
44 | P a g e

// Inline function definition


inline int square(int x) {
return x * x;
}

int main() {
int num = 5;

// Calling inline function


cout << "Square of " << num << " is: " << square(num) << endl;

return 0;
}
In this example, the function square() is defined as inline. When square(num) is called in
main(), the function call is replaced with the actual code of the function, num * num.

3.9 Friend Function

In C++, a friend function is a function that is not a member of a class but is allowed to access
the private and protected members of the class. Normally, private and protected members of a
class can only be accessed by the class’s own member functions, but by declaring a function as
a friend, it is granted special access rights.

A friend function is useful when an external function needs to work closely with the internals
of a class but should not be part of the class itself.

Syntax:

To declare a friend function, you use the friend keyword inside the class definition. The
function prototype is prefixed with the keyword friend.

class ClassName {
friend return_type function_name(parameters);
};
Key Characteristics of Friend Functions:
45 | P a g e

1. Not a Member Function: A friend function is not part of the class, even though it has
access to the class's private and protected members.

2. Access to Private/Protected Members: A friend function can access private and


protected data members directly.

3. Declared Inside Class, Defined Outside: Friend functions are declared inside the class
but defined outside like a regular function.

4. No this Pointer: Since a friend function is not a member function, it doesn’t have access
to the this pointer (used for referencing the current object in member functions).

Example:

#include <iostream>
using namespace std;

class MyClass {
private:
int num;

public:
MyClass(int n) : num(n) {}

// Friend function declaration


friend void showNumber(MyClass obj);
};

// Friend function definition


void showNumber(MyClass obj) {
// Can access private member 'num' directly
cout << "The number is: " << obj.num << endl;
}

int main() {
46 | P a g e

MyClass obj(42); // Create an object of MyClass


showNumber(obj); // Call the friend function

return 0;
}
 The showNumber() function is declared as a friend of the MyClass class.

 It can access the private member num of the MyClass object obj even though it is not
a member function.

 In the main() function, showNumber(obj) is called, and it prints the value of num.

Programs asked in PYQs


1. Write C++ code that defines a class and declares and array of objects to that
class.

#include <iostream>
using namespace std;

// Define a class
class Student {
private:
string name;
int age;

public:
// Constructor to initialize student data
Student(string n = "Unknown", int a = 0) {
name = n;
age = a;
}

// Function to display student information


47 | P a g e

void display() {
cout << "Name: " << name << ", Age: " << age << endl;
}
};

int main() {
// Declare an array of 3 Student objects
Student students[3] = {
Student("Alice", 20),
Student("Bob", 22),
Student("Charlie", 19)
};

// Access each object in the array and display their information


for (int i = 0; i < 3; i++) {
students[i].display();
}

return 0;
}
Output:
Name: Alice, Age: 20
Name: Bob, Age: 22
Name: Charlie, Age: 19

2. Write C++ code that defines a class and declares and array of objects to that
class.

#include <iostream>
using namespace std;

// Inline function to calculate the area of a triangle


48 | P a g e

inline float areaOfTriangle(float base, float height) {


return (0.5 * base * height);
}

int main() {
float base, height;

// Input the base and height of the triangle


cout << "Enter the base of the triangle: ";
cin >> base;
cout << "Enter the height of the triangle: ";
cin >> height;

// Call the inline function and display the result


cout << "The area of the triangle is: " << areaOfTriangle(base,
height) << endl;

return 0;
}
3. Write a C++ code that defines a class and declares an array of objects to that
class.

#include <iostream>
#include <string>
using namespace std;

class Book {
private:
string title;
string author;

public:
// Constructor to initialize Book
49 | P a g e

Book(string t, string a) : title(t), author(a) {}

// Function to display book details


void display() {
cout << "Title: " << title << ", Author: " << author << endl;
}
};

int main() {
// Declare an array of Book objects
Book books[3] = {
Book("1984", "George Orwell"),
Book("To Kill a Mockingbird", "Harper Lee"),
Book("The Great Gatsby", "F. Scott Fitzgerald")
};

// Display details of each book


for (int i = 0; i < 3; ++i) {
books[i].display();
}

return 0;
}
Output:
Title: 1984, Author: George Orwell
Title: To Kill a Mockingbird, Author: Harper Lee
Title: The Great Gatsby, Author: F. Scott Fitzgerald
4. Write a class ''Calculator'' with methods for addition, subtraction,
multiplication and division functions. Create a object to perform arithmetic
operation.
#include <iostream>
using namespace std;
50 | P a g e

// Define the Calculator class


class Calculator {
public:
// Method for addition
float add(float a, float b) {
return a + b;
}

// Method for subtraction


float subtract(float a, float b) {
return a - b;
}

// Method for multiplication


float multiply(float a, float b) {
return a * b;
}

// Method for division


float divide(float a, float b) {
if (b != 0)
return a / b;
else {
cout << "Error: Division by zero is undefined!" << endl;
return 0;
}
}
};

int main() {
Calculator calc; // Create an object of Calculator class
float num1, num2;
51 | P a g e

// Input two numbers from the user


cout << "Enter two numbers: ";
cin >> num1 >> num2;

// Perform and display arithmetic operations


cout << "Addition: " << calc.add(num1, num2) << endl;
cout << "Subtraction: " << calc.subtract(num1, num2) << endl;
cout << "Multiplication: " << calc.multiply(num1, num2) << endl;
cout << "Division: " << calc.divide(num1, num2) << endl;

return 0;
}
Output:
Enter two numbers: 10 5
Addition: 15
Subtraction: 5
Multiplication: 50
Division: 2
5. Write a class ''Calculator'' with methods for addition, subtraction,
multiplication and division functions. Create a object to perform arithmetic
operation.

#include <iostream>
using namespace std;

// Define the Student class


class Student {
private:
string name;
int rollNumber;
float marks;
52 | P a g e

public:
// Member function to set student details
void setDetails(string n, int r, float m) {
name = n;
rollNumber = r;
marks = m;
}

// Member function to display student details


void displayDetails() {
cout << "Student Name: " << name << endl;
cout << "Roll Number: " << rollNumber << endl;
cout << "Marks: " << marks << endl;
}
};

int main() {
Student student1; // Create an object of Student class

// Set details of the student using the setDetails function


student1.setDetails("John Doe", 101, 88.5);

// Display the details of the student


student1.displayDetails();

return 0;
}
Output:
Student Name: John Doe
Roll Number: 101
53 | P a g e

Mark: 88.5
6. Write a class ''Calculator'' with methods for addition, subtraction,
multiplication and division functions. Create a object to perform arithmetic
operation.

#include <iostream>
using namespace std;

// Function to swap two integers


void swap(int &a, int &b) {
int temp = a;
a = b;
b = temp;
}

// Function to swap two floats


void swap(float &a, float &b) {
float temp = a;
a = b;
b = temp;
}

// Function to swap two characters


void swap(char &a, char &b) {
char temp = a;
a = b;
b = temp;
}

int main() {
// Swapping integers
int int1 = 10, int2 = 20;
54 | P a g e

cout << "Before swapping integers: " << int1 << " and " << int2
<< endl;
swap(int1, int2);
cout << "After swapping integers: " << int1 << " and " << int2 <<
endl << endl;

// Swapping floats
float float1 = 1.5, float2 = 2.5;
cout << "Before swapping floats: " << float1 << " and " << float2
<< endl;
swap(float1, float2);
cout << "After swapping floats: " << float1 << " and " << float2
<< endl << endl;

// Swapping characters
char char1 = 'A', char2 = 'B';
cout << "Before swapping characters: " << char1 << " and " <<
char2 << endl;
swap(char1, char2);
cout << "After swapping characters: " << char1 << " and " << char2
<< endl;

return 0;
}
Output:
Before swapping integers: 10 and 20
After swapping integers: 20 and 10

Before swapping floats: 1.5 and 2.5


After swapping floats: 2.5 and 1.5

Before swapping characters: A and B


After swapping characters: B and A

You might also like