0% found this document useful (0 votes)
83 views76 pages

Object Oriented Programming in C++ - I B.SC AI & ML Material

The document outlines the syllabus for an Object Oriented Programming course in C++ at Valluvar College of Science and Management. It covers key concepts such as classes, objects, inheritance, polymorphism, and control structures, along with practical applications and advantages of OOP. Additionally, it provides an introduction to C++, its features, and basic I/O operations.

Uploaded by

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

Object Oriented Programming in C++ - I B.SC AI & ML Material

The document outlines the syllabus for an Object Oriented Programming course in C++ at Valluvar College of Science and Management. It covers key concepts such as classes, objects, inheritance, polymorphism, and control structures, along with practical applications and advantages of OOP. Additionally, it provides an introduction to C++, its features, and basic I/O operations.

Uploaded by

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

Valluvar College of Science and Management

(Autonomous)

KARUR-3

CLASS: I B.Sc(AI & ML)

SUBJECT: Object Oriented Programming in C++

SUBJECT CODE:25UAIC01

Prepared by

Dr.G.Sudhadevi M.Sc.,M.Phil.,B.Ed.,Ph.D.,
Assistant Professor

Department of Computer Science and Applications


SYLLABUS

Object Oriented Programming in C++

UNIT-1

Introduction to C++ - Key concepts of Object-Oriented Programming –Advantages – Object-Oriented


Languages – I/O in C++ – C++ Declarations. Control structures: Decision Making and Statements:
If...Else, jump, goto, break, continue, switch case statements.

Loops in C++: for, while, do-while Functions in C++: Inline functions – Function Overloading.

UNIT-II

Classes and Objects: Declaring Objects – Defining Member Functions –Static Member variables and
functions – Array of objects – Friend functions – Overloading member functions – Bit fields and
classes –Constructor and destructor with static members.

UNIT-III

Operator Overloading: Overloading unary and binary operators –Overloading friend functions- Type
conversion. Inheritance: Types of Inheritance–Single, Multilevel, Multiple, Hierarchical, Hybrid,
Multi-path inheritance – Virtual base classes –Abstract classes.

UNIT-IV

Pointers – Declaration – Pointer to class, object – This pointer – Pointers to derived classes and base
classes – Arrays – Characteristics – Array of classes – Memory models – new and delete operators –
Dynamic objects – Binding ,Polymorphism, and Virtual Functions.

UNIT-V

Files – File stream classes – File modes – Sequential Read/Write operations– Binary and ASCII files –
Random access operation – Templates –Exception handling – String – Declaring and initializing string
objects –String attributes – Miscellaneous functions.
OBJECT ORIENTED PROGRAMMING IN C++
UNIT -1

Introduction to C++ - Key concepts of Object-Oriented Programming – Advantages – Object-


Oriented Languages – I/O in C++ – C++ Declarations. Control Structures: Decision Making and
Statements: If...Else, jump, goto, break, continue, switch case statements. Loops in C++: for, while,
do-while .Functions in C++: Inline functions – Function Overloading.

INTRODUCTION TO C++
C++ is a general-purpose programming language that was developed by Bjarne Stroustrup as an
enhancement of the C language to add object-oriented paradigm. It is a high-level programming
language that was first released in 1985.

Features of C++

The main features C++ programming language are as follows:

Simple: It is a simple language in the sense that programs can be broken down into logical units
and parts, and has a rich library support and a variety of datatypes.
Machine Independent: C++ code can be run on any machine as long as a suitable compiler is
provided.
Low-level Access: C++ provides low-level access to system resources, which makes it a suitable
choice for system programming and writing efficient code.
Fast Execution Speed: C++ is one of the fastest high-level languages. There is no additional
processing overhead in C++, it is blazing fast.
Object-Oriented: One of the strongest points of the language which sets it apart from C. Object-
Oriented support helps C++ to make maintainable and extensible programs. i.e. large-scale
applications can be built.
Applications of C++

1. Real time system


2. Simulation and modeling
3. AI and expert system
4. Neural network programming.
5. CAD/CAM systems.

Key Concepts of object oriented programming

Object-Oriented Programming (OOP) is a programming paradigm that revolves around


the concept of "objects." These objects encapsulate both data (attributes) and the functions
(methods) that operate on that data. C++ supports OOP through several key concepts:
Classes and Objects
Class: A blueprint for creating objects, defining their data and methods.

Example:
class Car {
public:
string brand;
void startEngine() {
cout<< "Engine started" <<endl;
}
};
Object: An instance of a class, representing a specific entity.

Car myCar;
myCar.brand = "Toyota";
myCar.startEngine();

Encapsulation
Bundling data and methods within a class, controlling access to data using access modifiers
(public, private, protected).
Promotes data hiding and security.
Class BankAccount {
private:
double balance;
public:
void deposit(double amount) { balance += amount; }
double getBalance() { return balance; }
};

Inheritance
A mechanism where a class (derived class) inherits properties and methods from another class
(base class).Supports code reusability and hierarchical relationships between classes.
class Vehicle {
public:
void honk() { cout<< "Beep!" <<endl; }
};
class Car : public Vehicle {};
Polymorphism
The ability of objects to take on multiple forms. Achieved through function overloading (compile-time)
and function overriding (run-time).

Example: Function overloading

Class Print {
public:
void show(inti)
{ cout<<i;
}
void show(double d)
{ cout<< d; }};
Abstraction
Hiding complex implementation details and exposing only essential features. Achieved through
abstract classes and interfaces, simplifying code usage.
class Shape {
public:
virtual void draw() = 0; // Pure virtual function
};
Modularity
Structuring code into independent and reusable modules (classes and objects).Enhances code
organization and maintainability.
ADVANTAGES OF OOPS IN C++
1. Code Reusability:
OOP allows for the creation of reusable components through inheritance and polymorphism.
Classes and objects can be reused across different projects or applications, reducing redundancy and
saving development time.
2. Modularity:
OOP promotes modularity by breaking down complex systems into smaller, manageable units
(classes and objects). Each object encapsulates its data and behavior, making it independent and easier to
develop, maintain, and debug.
3. Encapsulation:
OOP's encapsulation feature hides implementation details and protects data by restricting access
to it. This enhances data security and integrity by preventing unauthorized modifications.
4. Easier Maintenance:
The modular nature of OOP makes it easier to maintain and update code. Changes can be made
to specific objects or classes without affecting other parts of the system.
5. Improved Code Organization:
OOP promotes a structured and organized approach to programming, making it easier to
understand and navigate complex code. This leads to better collaboration among developers and reduces
the risk of errors.
6. Enhanced Problem-Solving:
OOP aligns well with real-world problem-solving, as it allows programmers to model real-world
entities and their interactions using classes and objects. This can make it easier to understand and solve
complex problems.
7. Scalability:
OOP allows for the creation of scalable systems that can easily adapt to changing requirements.
New objects and classes can be added to the system without disrupting existing functionality.
8. Flexibility:
OOP supports flexibility through polymorphism, which allows objects of different classes to be
treated as instances of a common superclass. This enables dynamic and flexible code that can adapt to
different situations.
9. Efficient Collaboration:
OOP's modularity and encapsulation promote efficient collaboration among developers by
clearly defining the responsibilities of each object or class. This can lead to faster development cycles
and reduced errors.
10. Improved Productivity:
OOP can lead to increased productivity by reducing the need to rewrite code and making it easier
to maintain and debug. Developers can focus on creating reusable components and building scalable
systems, rather than repetitive tasks.

I/O IN C++
In C++, I/O (Input/Output) operations are handled using streams provided by
the <iostream> library. Here’s a quick overview of how input and output work in C++:
Basic Input and Output
 std::cout: Used for output (printing to the console).
 std::cin: Used for input (reading from the console).

include<iostream>
int main() {
int number;
cout<< "Enter a number: "; // Output
cin>> number; // Input
cout<< "You entered: " << number; // Output
return 0;}
C++ DECLARATIONS

C++ declarations introduce names into a program, associating them with specific types and
attributes. They inform the compiler about the existence of entities like variables, functions, and classes,
enabling their subsequent use.
Types of Declarations:
i). Variable Declarations: Specify the name and type of a variable, optionally initializing it with a
value. For example:

double price = 19.99; // Declares a double variable named price and initializes it
ii).Function Declarations: Declare the function's name, return type, and parameters (if any) without
providing the function's body. For example:
int add(int a, int b); // Declares a function named add that takes two integers and returns an integer
iii).Class Declarations: Introduce a new class type, specifying its members (data and functions). For

Example:

Class MyClass{
public:
int value;
void printValue();
};

CONTROL STRUCTURES
Control structures in C++ dictate the order in which statements are executed. They are essential
for creating programs that can make decisions, repeat actions, and manage program flow.
There are three main types of control structures in C++:
1. Sequential Control Structure:
 Executes statements in the order they appear in the code, one after the other.
 This is the default flow of execution, where each instruction is carried out sequentially.
2. Selection Control Structure (Decision-Making):
 Allows the program to choose between different paths of execution based on conditions.
 Key statements include:
 if: Executes a block of code if a condition is true.
 if-else: Executes one block of code if a condition is true and another block if it is false.
 else if: Provides additional conditions to check if the initial if condition is false.
 switch: Selects one block of code to execute from multiple options based on the value of a
variable.
3. Iteration Control Structure (Loops):
 Repeats a block of code multiple times until a condition is met.
 Key loop statements include:
 for: Repeats a block of code a specific number of times, often used with a counter variable.
 while: Repeats a block of code as long as a condition is true.
 do-while: Similar to while, but executes the block of code at least once, checking the condition
at the end of each iteration.
Other Control Statements:
 break: Terminates the execution of a loop or switch statement.
 continue: Skips the current iteration of a loop and continues with the next one.
 goto: Transfers control to a labeled statement (generally avoided in modern programming due to
its potential to complicate code flow).

Decision Making and Statements


Decision-making in C++ involves using conditional statements to control the flow of program
execution based on specific conditions. These statements allow programs to make choices and execute
different code blocks depending on whether a condition is true or false.
Here are the primary decision-making statements in C++:
1. if Statement:
Executes a block of code if a specified condition is true
Syntax
if (condition) {
// Code to execute if condition is true
}
Example:
#include <iostream>
int main() {
int score = 75;
if (score >= 60) {
std::cout << "Congratulations! You passed." << std::endl;
}
std::cout << "Program finished." << std::endl;
return 0;
}
2. if-else Statement:
Executes one block of code if a condition is true and another block if the condition is false.
Syntax

if (condition) {
// Code to execute if condition is true
} else {
// Code to execute if condition is false
}
Example:
#include <iostream>
int main() {
int score;
cout << "Enter a student's score: ";
cin >> score;
// Check if the score is greater than or equal to 60 for a passing grade
if (score >= 60) {
std::cout << "The student passed the exam." << std::endl;
} else {
std::cout << "The student failed the exam." << std::endl; }
return 0; }

3.if-else-if Ladder:
Allows for multiple conditions to be checked sequentially
Syntax
if (condition1) {
// Code to execute if condition1 is true
} else if (condition2) {
// Code to execute if condition2 is true
} else if (condition3) {
// Code to execute if condition3 is true
} else {
// Code to execute if none of the above conditions are true
}
Example:
#include <iostream>
int main() {
int score;
cout << "Enter the student's score: ";
cin >> score;
if (score >= 90) {
std::cout << "Grade: A" << std::endl;
} else if (score >= 80) {
std::cout << "Grade: B" << std::endl;
} else if (score >= 70) {
std::cout << "Grade: C" << std::endl;
} else if (score >= 60) {
std::cout << "Grade: D" << std::endl;
} else {
std::cout << "Grade: F" << std::endl;
}
return 0;
}
4. Nested if Statements:
An if statement can be placed inside another if or else block.
Syntax:

if (condition1) {
if (condition2) {
// Code to execute if both condition1 and condition2 are true
}
else {
// Code to execute if condition1 is true and condition2 is false
}
}
else {
// Code to execute if condition1 is false
}
Example:
#include <iostream>
int main() {
int age = 20;
bool hasDrivingLicense = true;
if (age >= 18) {
cout << "You are old enough to drive." << endl;
// Inner if statement: Check if the person has a driving license
if (hasDrivingLicense) {
cout << "You have a driving license and can legally drive." <<endl;
} else {
cout << "You are old enough but do not have a driving license." << endl;
}
} else {
cout << "You are not old enough to drive." << endl;
}
return 0;
}
5. Switch Statement:
Allows for selection from multiple code blocks based on the value of an expression.
Syntax:

switch (expression) {
case value1:
// Code to execute if expression == value1
break;
case value2:
// Code to execute if expression == value2
break;
default:
// Code to execute if expression does not match any case
break; }
Example:

#include <iostream>
int main() {
int dayNumber;
// Prompt the user to enter a number for the day
cout << "Enter a number (1-7) to represent a day of the week: ";
cin >> dayNumber;
// Use a switch statement to determine the day name
switch (dayNumber) {
case 1:
cout << "It's Monday!" << std::endl;
break; // Exit the switch statement after this case
case 2:
cout << "It's Tuesday!" << std::endl;
break;
case 3:
cout << "It's Wednesday!" << std::endl;
break;
case 4:
cout << "It's Thursday!" << std::endl;
break;
case 5:
cout << "It's Friday!" << std::endl;
break;
case 6:
cout << "It's Saturday!" << std::endl;
break;
case 7:
cout << "It's Sunday!" << std::endl;
break;
default: // Executed if none of the above cases match
cout << "Invalid day number. Please enter a number between 1 and 7." << std::endl;
break;
}
return 0;}
6. Conditional (Ternary) Operator: A shorthand for a simple if-else statement
Syntax:
condition ? expression_if_true : expression_if_false;
Example:
#include <iostream>
int main() {
int score = 75;
std::string result;
// Using the conditional operator to determine if the student passed or failed
result = (score >= 60) ? "Passed" : "Failed";
std::cout << "The student's score is: " << score << std::endl;
std::cout << "The student " << result << "." << std::endl;
// Another example: finding the maximum of two numbers
int num1 = 10;
int num2 = 25;
int max_value;
max_value = (num1 > num2) ? num1 : num2;
cout << "The maximum val between "<< num1<<" and "<< num2 << " is: "<< max_value << ;
return 0; }
7. Jump Statements:
 break: Terminates the loop or switch statement
 continue: Skips the current iteration of the loop
 goto: Transfers control to a labeled statement (generally discouraged)
 return: Exits the current function

LOOPS IN C++
In C++, loops are control flow structures that allow you to execute a block of code repeatedly
based on a specified condition. They automate repetitive tasks and make code more efficient. There are
three main types of loops in C++:
i). for loop:
 Used when the number of iterations is known beforehand.
 Consists of three parts:
 Initialization: Executed once at the beginning.
 Condition: Evaluated before each iteration; the loop continues if true.
 Increment/Decrement: Executed after each iteration.
Syntax:
for (initialization; condition; increment/decrement) {
// code to be executed
}
Example:
for (inti = 0; i< 5; i++) {
std::cout<< "Hi\n";
}
This will print "Hi" 5 times.
ii). While loop:

 Used when the number of iterations is not known beforehand.


 The loop continues as long as the condition is true.
Syntax:
while (condition) {
// code to be executed
}
Example:
int i = 0;
while (i< 5) {
cout<<i<< "\n"; i++;
}
In the example below, the code in the loop will run, over and over again, as long as a variable ( i)
is less than 5:

iii).Do-While Loop
In C++, the do-while loop is an exit-controlled loop that repeatedly executes a block of code at
least once and continues executing as long as a given condition remains true. Unlike the while loop,
the do-while loop guarantees that the loop body will execute at least once, regardless of whether the
condition is true or false.
Syntax:
do {
// Body of the loop
// Update expression
} while (condition);
Example:
int main() {
// do-while loop to print "Hi" 5 times
int i = 0;
do {
cout<< "Hi" <<endl;
i++;
} while (i< 3);
return 0;
}
Output:Hi
Hi
Hi

FUNCTIONS IN C++
In C++, functions are blocks of code designed to perform specific tasks. They help in organizing
code, improving readability, and enabling reusability.
i). Function Declaration (Prototype)
A function must be declared before it is used. The declaration specifies the function's name, return type,
and parameters.
return_typefunction_name(parameter_list);
int add(int a, int b);
Example:
int add(int a, int b);
ii).Function Definition
The function definition contains the actual code that executes when the function is called.
return_type function_name(parameter_list){
// Function body
return value; // Optional, based on return type
}

Example:
int add(int a, int b){
return a + b;
}
iii). Function Call
To execute a function, you call it by its name and pass the required arguments.
Example:
int result = add(5, 3); // Calls the 'add' function

Example:

#include <iostream>
using namespace std;
// declaring a function
void greet() {
cout << "Hello there!";
}
int main() {
// calling the function
greet();
return 0;
}

Types of functions
 Inline Functions: Functions defined with the inline keyword to reduce function call overhead.
 Friend Functions: Functions declared as friend to access private/protected members of a class.
 Virtual Functions: Functions in a base class that can be overridden in derived classes, enabling
runtime polymorphism.
 Pure Virtual Functions: Declared with = 0 in abstract classes, forcing derived classes to
implement them.
 Static Functions: Functions that belong to a class but do not operate on class instances.
 Lambda Functions: Anonymous functions defined using the [] syntax for short, inline
operations.

INLINE FUNCTIONS
In C++, an inline function is a function for which the compiler attempts to expand the function's
code at the point of each call, rather than performing a traditional function call. This can reduce the
overhead of function calls, especially for small, frequently used functions.
Syntax
inline int add(int a, int b) {
return a + b;
}
Example
#include <iostream>
inline int square(int x) {
return x * x;
}
int main() {
int num = 5;
cout<< "Square of " << num << " is " << square(num) <<endl;
return 0;}
FUNCTION OVERLOADING IN C++
Function overloading in C++ allows multiple functions to have the same name but different
parameters (number or type). The compiler differentiates them based on their function signature (i.e., the
types and number of parameters).
Rules of Overloading
1. Functions must differ by number or type of parameters.
2. Return type alone is not sufficient to overload a function.

Syntax
// Function declarations (same name, different parameters)
return_typefunction_name(parameter_list1);
return_typefunction_name(parameter_list2);
Example:
Function overloading using different types of parameters
#include<iostream>
// function with float type parameter
float absolute (float var){
if(var<0.0)
var=-var;
return var;}
// function with int type parameter
int absolute(intvar){
if(var<0)
var=-var;
returnvar;}
int main(){
// call function with int type parameter
cout<<”Absolute value of -5=”<<absolute(-5)<<endl;
//call function with float type parameter
cout<<”Absolute value of 5.5=”<<absolute(5.5f)<<endl;return 0;
}
QUESTIONS
UNIT -1

1. Multiple Choice Questions (MCQs)


1. Which of the following is not a basic concept of OOP?
A) Encapsulation B) Polymorphism
C) Inheritance D) Compilation
Ans: D
2. What is the correct syntax for outputting “Hello World” in C++?
A) cout<< "Hello World"; B) printf("Hello World");
C) echo "Hello World"; D) System.out.println("Hello World");
Ans: A
3. Which control statement is used to exit a loop in C++?
A) continue B) break C) goto D) return
Ans: B
4. Which keyword is used to define an inline function in C++?
A) inline B) function C) define D) static
Ans: A
5. Which concept allows functions to have the same name but different parameters?
A) Function overriding B) Function overloading
C) Inheritance D) Polymorphism
Ans: B
6. Who developed C++?.

Ans: Bjarne Stroustrup


7. Name the object oriented programming language other than c++.
Ans: Java (or Python, C#, Smalltalk).
8. Which keyword is used to make a decision based on a condition in C++?
Ans: if.
9. What does the continue statement do in a loop?
Ans: Skips the rest of the current iteration and proceeds to the next iteration.

2. Fill in the blanks


1. The ___ statement is used to transfer control to another part of the program.
Ans: goto
2. C++ is an ___ oriented programming language.
Ans: object
3. The keyword used to declare input/output stream in C++ is ___.
Ans: iostream
4. The ___ loop checks the condition after executing the loop body.
Ans: do-while
5. In C++, ___ allows you to use the same function name with different argument types.
Ans: Function overloading
3. Two Marks Questions
1. Define Object-Oriented Programming.
2. Give any two applications of OOP.
3. Mention any two advantages of using C++ over C.
4. Write any four features of OOP.
5. What is the use of break and continue in loops?
6. Define inline function with an example.
7. What is function overloading in C++?
8. What is a scope resolution operator?
9. What are the data types in C++?
10. How to declare a variable in C++?

4. Five Marks Questions


1. Write a program in C++ to check whether a number is even or odd using if-else.
2. Explain the difference between for, while, and do-while loops with syntax.
3. Discuss the key features of Object-Oriented Programming.
4. Explain function overloading with two examples.
5. Write a short note on I/O operations in C++ using cin and cout.

5. Ten Marks Questions


1. Compare Procedural and Object-Oriented Programming Paradigms. Provide examples to justify
your answer.
2. Design and implement a C++ program that demonstrates the use of all control statements (if-else,
switch, break, continue, and goto).
3. Write a complete C++ program that accepts input from the user, processes it using functions
(inline and overloaded), and displays the result.
4. Evaluate the advantages of Object-Oriented Languages in terms of reusability, scalability, and
maintenance. Provide real-life scenarios.
5. Create a C++ program that demonstrates the use of different types of loops by printing a number
pattern. Explain your logic.
UNIT –II

Classes and Objects: Declaring Objects – Defining Member Functions – Static Member variables
and functions – Array of objects – Friend functions – Overloading member functions – Bit fields and
classes – Constructor and destructor with static members.
Classes and Objects
In C++, declaring objects means creating an instance of a class. Once you define a class, you
can create objects (instances) of that class to use its data and functions.
Basic Object Declaration
To declare a single object, you use the following syntax:
ClassName objectName;
Or with constructor arguments:
ClassName objectName(arg1, arg2, ...);
Example:
#include <iostream>
class Car {
public:
string brand;
int year;
// Constructor
Car(string b, int y) {
brand = b;
year = y;
}
void display() {
cout << "Brand: " << brand << ", Year: " << year << endl;
}
};
int main() {
// Declare an object of class Car
Car car1("Toyota", 2020);
// Use the object
car1.display();
return 0;
}
Defining member function
In C++, a member function is a function that is part of a class. You can define member
functions in two main ways:
1.Inside the class definition
When you define a function directly in the class body, it is automatically treated as inline.
#include <iostream>
class MyClass {
public:
void sayHello() {
cout << "Hello from inside the class!" << endl;
}
};
2.Outside the class definition

You declare the function in the class, then define it outside using the scope resolution
operator ::

#include <iostream>
class MyClass {
public:
void sayHello(); // Declaration
};
// Definition outside the class
void MyClass::sayHello() {
cout << "Hello from outside the class!" << endl;
}

Features
 Member functions can access private and protected data of the class.
 You can also define const, static, or virtual member functions.
 Constructors and destructors are also special kinds of member functions.

Static member variables and functions


Static member variables
A static member variable is shared across all objects of a class. It belongs to the class itself,
not any particular instance.
Key Points:
 Only one copy exists for all objects.
 Shared among all instances of the class.
 Can be accessed using the class name.
 Must be defined outside the class if it's a non-const static variable (in C++).

Example:
class Counter {
public:
static int count;
Counter() {
count++;
}
void showCount() {
std::cout << "Count: " << count << std::endl;
}
};

// Definition of static member outside the class


int Counter::count = 0;
int main() {
Counter a, b, c;
a.showCount(); // Output: Count: 3
b.showCount(); // Output: Count: 3
return 0;}

Static member functions


Do not require an object to be called: Can be called using the class name.
Can only access static members: They don't have access to this pointer.
class MyClass {
public:
static void showCount();
};
void MyClass::showCount() {
std::cout << "Count is: " << count << std::endl;}

Array of Objects

In C++, an array of objects is a collection of objects of the same class type stored in contiguous
memory locations. This is useful when you want to manage multiple objects using an indexed structure.

Syntax
ClassName ObjectName[number of objects];

Example:

#include<iostream>
class Employee{
int id;
char name[30];
public:
// Declaration of function
void getdata();
// Declaration of function
void putdata();};
// Defining the function outside
// the class
void Employee::getdata(){
cout << "Enter Id : ";
cin >> id;
cout << "Enter Name : ";
cin >> name;}
// Defining the function outside
// the class
void Employee::putdata(){
cout << id << " ";
cout << name << " ";
cout << endl;}
int main(){
// This is an array of objects having
// maximum limit of 30 Employees
Employee emp[30];
int n, i;
cout << "Enter Number of Employees - ";
cin >> n;
// Accessing the function
for(i = 0; i < n; i++)
emp[i].getdata();
cout << "Employee Data - " << endl;
// Accessing the function
for(i = 0; i < n; i++)
emp[i].putdata();
}
Friend functions

In C++ (and some other object-oriented languages), friend functions are functions that are not
members of a class but still have access to the class's private and protected members. This is useful
when you want to allow a function (or another class) to access the internals of a class without making
those members public.

Syntax:

class ClassName {
private:
// Private members
public:
// Public members
friend return_type functionName(parameters); // Declaration of friend function
};
// Definition of the friend function (outside the class)
return_type functionName(parameters) {
// Access private/protected members of ClassName objects
}

Example:

class B; // Forward declaration


class A {
private:
int data = 10;
// Friend function of both classes
friend void showData(A, B);
};
class B {
private:
int value = 20;
friend void showData(A, B);
};
void showData(A a, B b) {
std::cout << "A's data: " << a.data << "\n";
std::cout << "B's value: " << b.value << "\n"; }

Overloading member functions


Overloading member functions in C++ (or other object-oriented languages like Java) refers to
defining multiple functions with the same name in a class but with different parameter lists (either in
number, type, or order of parameters). The compiler determines which function to call based on the
arguments used in the function call — this is known as compile-time polymorphism.
Key Points:
 Function name must be the same
 Parameter list must differ (number or type/order of parameters)
 Return type can be different, but cannot be used alone to distinguish overloads

#include <iostream>
class Print {
public:
void show(int i) {
cout << "Integer: " << i << endl;
}
void show(double d) {
cout << "Double: " << d << endl;
}
void show(string s) {
cout << "String: " << s << endl;
}
};
int main() {
Print obj;
obj.show(10); // Calls show(int)
obj.show(3.14); // Calls show(double)
obj.show("Hello"); // Calls show(string)
return 0; }

Bit fields and Classes

Bit fields in C++ are a way to use individual bits (or a small number of bits) to represent data
within a class or struct. This can save memory when you want to store multiple small-sized variables
(like flags or small enums) together
.
Bit Fields in Structs/Classes

Bit fields are typically used in structs but can also be used in classes. Here's the basic syntax:
Syntax:
struct Flags {
unsigned int flag1 : 1; // Uses 1 bit
unsigned int flag2 : 2; // Uses 2 bits
unsigned int flag3 : 5; // Uses 5 bits
};
Example:

#include <iostream>
struct Status {
unsigned int error : 1;
unsigned int ready : 1;
unsigned int command : 4;
};
int main() {
Status s{};
s.error = 1;
s.ready = 0;
s.command = 9;
std::cout << "Error: " << s.error << "\n";
std::cout << "Ready: " << s.ready << "\n";
std::cout << "Command: " << s.command << "\n";
return 0;
}

Bit Fields in Classes

You can use bit fields inside a class just like a struct, but you often make the fields private and
access them
class Packet {
private:
unsigned int version : 3;
unsigned int type : 5;
public:
void setVersion(unsigned int v) { version = v & 0x7; } // mask to 3 bits
void setType(unsigned int t) { type = t & 0x1F; } // mask to 5 bits
unsigned int getVersion() const { return version; }
unsigned int getType() const { return type; }
};

Constructor and Destructor with static member

In C++, constructors, destructors, and static members have unique characteristics that are
important to understand when used together.

Constructor and Destructor with static Members in C++


Static Members belong to the class, not any instance.
They are shared among all instances.
A static data member must be declared inside the class but defined outside.
Constructors and destructors cannot initialize static data members directly.
However, constructors/destructors can access and modify static members.

Example:
#include <iostream>
class Counter {
private:
int id;
static int count; // Static member declaration
public:
Counter() {
count++;
id = count;
cout << "Constructor called for object " << id << endl;
}
~Counter() {
cout << "Destructor called for object " << id << endl;
count--;
}
static void showCount() {
cout << "Current count: " << count << endl;
}
};
// Static member definition
int Counter::count = 0;
int main() {
Counter::showCount(); // Output: 0
Counter c1;
Counter c2;
Counter::showCount(); // Output: 2
{
Counter c3;
Counter::showCount(); // Output: 3
} // Destructor for c3 is called here
Counter::showCount(); // Output: 2
return 0;}

Questions
UNIT II
Multiple choice questions
1. Which of the following is the correct way to declare an object in C++?
a) class obj; b) obj class; c) Class obj; d) ClassName obj;
Answer: d) ClassName obj;
2. What is a static member variable?
a) A variable that changes with every object
b) A variable shared by all objects of a class
c) A variable local to main d) A constant variable
Answer: b) A variable shared by all objects of a class
3. Which function is called automatically when an object is created?
a) Destructor
b) Member function
c) Constructor
d) Friend function
Answer: c) Constructor

4. Which keyword is used to make a function a friend of a class?


a) friend
b) private
c) public
d) protected
Answer: a) friend
5. Bit fields in classes are used to:
a) Create multiple objects
b) Overload operators
c) Save memory by packing data
d) Write inline functions
Answer: c) Save memory by packing data
Two Mark Questions
1. Define an object in C++ with an example.
2. What is the purpose of a static data member?
3. Differentiate between constructor and destructor.
4. Write a syntax of a friend function.
5. What is function overloading?
6. What is a static member variable?
7. What is the purpose of a constructor?
8. What is a destructor?
9. What is an array of objects? Give an example.
Five Mark Questions
1. Explain the concept of static member variables and static member functions with a sample
program.
2. How is an array of objects declared and accessed in C++? Provide an example.
3. What are friend functions? Discuss their use with an example.
4. Write a program to overload a function display() for different parameter types.
5. Discuss bit fields in C++ classes. How are they useful?
6. Write a C++ program that demonstrates the following concepts:
1. Static member variables and static member functions
2. Constructor and destructor
3. Overloaded member functions
7. Design a class Employee with the following:
1. Data members: emp_id, name, salary
2. Static data member: count to track number of employees
3. Member functions: getData(), displayData()
4. Use friend function to access private members
5. Include constructor, destructor, and array of objects
8. Explain in detail the concept of function overloading and how it differs from operator
overloading. Give at least two examples.
9. Discuss the life cycle of a class object with constructors and destructors. Include the behavior of
static members within it.

Ten mark questions

1. Explain the concept of classes and objects in C++.


2. Discuss the role of static member variables and functions.
3. What is meant by array of objects in C++?.How is different from single object?.
4. Write a program to store and display details of five employees using an array of objects.
5. What is a friend function in C++? What are its advantages and limitations?
6. Define function overloading. How can member functions be overloaded within a class?

7. Explain the use of constructors and destructors in C++.


8. How can static members be initialized using constructors?
9. What are bit fields in C++? How are they used within classes to optimize memory usage?
\

Object Oriented Programming in C++

UNIT -III

Operator Overloading: Overloading unary and binary operators – Overloading friend functions Type
conversion.Inheritance: Types of Inheritance – Single, Multilevel, Multiple, Hierarchical, Hybrid,
Multi-path inheritance – Virtual base classes – Abstract classes.

Overloading unary and binary operators in c


Operator overloading in C++ allows you to define how operators (like +, -, *, ++, etc.) behave for
your own user-defined types (usually classes). There are two kinds of operators you can overload:
Unary Operators:
Unary operators operate on a single operand. Examples include:
 - (unary minus)
 ! (logical NOT)
 ++ (increment)
 -- (decrement)

#include <iostream>
class Number {
int value;
public:
Number(int v) : value(v) {}
// Overload unary -
Number operator-() const {
return Number(-value);
}
void display() const {
cout << value << endl;
}
};
int main() {
Number num(10);
Number neg = -num;
neg.display(); // Output: -10
return 0;
}
Binary Operators
Binary operators operate on two operands. Examples include:
 +, -, *, /, %
 ==, !=, <, >
 =, +=, etc.

Example:
#include <iostream,h>
class Complex {
float real, imag;
public:
Complex(float r = 0, float i = 0) : real(r), imag(i) {}
// Overload +
Complex operator+(const Complex& c) const {
return Complex(real + c.real, imag + c.imag);
}
void display() const {
cout << real << " + " << imag << "i" << endl;
}
};
int main() {
Complex c1(1.5, 2.5), c2(2.5, 1.5);
Complex c3 = c1 + c2;
c3.display(); // Output: 4 + 4i
return 0;
}

Overloading friend functions

Overloading friend functions in C++ is possible and follows the same rules as normal function
overloading — the function name remains the same, but the parameter list must differ. Since friend
functions are not member functions, they are defined outside the class, but they are granted access to the
class’s private and protected members.

Key Points:
 Overloading works by changing the parameter list — the compiler chooses the correct
function based on arguments.
 Friend functions must be declared in the class if they need access to private/protected
members.
 They are not members of the class, so overloading is done globally (outside the class scope).

Example

#include <iostream>
class Box {
int length;
public:
Box(int l) : length(l) {}
// Friend function declarations
friend void print(Box b);
friend void print(Box b1, Box b2);
};
// Friend function with one parameter
void print(Box b) {
cout << "Length of box: " << b.length << endl;
}
// Overloaded friend function with two parameters
void print(Box b1, Box b2) {
cout << "Sum of lengths: " << b1.length + b2.length << endl;
}
int main() {
Box b1(10), b2(20);
print(b1); // Calls print(Box)
print(b1, b2); // Calls print(Box, Box)
return 0;
}

Type conversion
Type conversion (also called type casting) is the process of converting a value from one data
type to another in programming.
Two Types of Type Conversion:
1.Implicit Conversion (Type Coercion)
 Done automatically by the compiler/interpreter.
 Happens when mixing different data types in expressions.
 Safe conversions (e.g., from int to float).

Example
 x = 10 # int
 y = 2.5 # float
 result = x + y # x is automatically converted to float
 print(result) # 12.5 (float)

Example:
#include <iostream>
int main() {
int integerValue = 10;
double doubleValue = 5.5;
// Implicit conversion: integerValue is promoted to double for addition
double sum = integerValue + doubleValue;
std::cout << "Integer value: " << integerValue << std::endl;
std::cout << "Double value: " << doubleValue << std::endl;
std::cout << "Sum (double): " << sum << std::endl; // Output: 15.5
chr characterValue = 'A';
int asciiValue = characterValue; // Implicit conversion: char to int (ASCII value)
td::cout << "Character value: " << characterValue << std::endl;
std::cout << "ASCII value: " << asciiValue << std::endl; // Output: 65
return ;
}

2.Explicit Conversion (Type Casting)


 Done manually by the programmer using built-in functions or casting methods.

Example:
x = 10
y = "20"
result = x + int(y) # convert string to int
print(result) # 30

Example:

#include <iostream>
int main() {
double pi = 3.14159;
// Explicit conversion: double to int using static_cast
int roundedPi = static_cast<int>(pi);
std::cout << "Original double: " << pi << std::endl;
std::cout << "Rounded int: " << roundedPi << std::endl; // Output: 3 (truncation)
int number = 66;
// Explicit conversion: int to char using static_cast
char character = static_cast<char>(number);
std::cout << "Original int: " << number << std::endl;
std::cout << "Converted char: " << character << std::endl; // Output: B
return 0;
}
Inheritance in C++
Inheritance in C++ is a fundamental concept of object-oriented programming (OOP) that
allows a class (called a derived class or child class) to inherit properties and behaviors (data members
and member functions) from another class (called a base class or parent class).
Syntax:
class Base {
public:
void show() {
std::cout << "Base class function" << std::endl;
}
};

class Derived : public Base {


// Inherits the show() function
};
Types of Inheritance

1.Single Inheritance

class A { };
class B : public A { };

2.Multilevel Inheritance

class A { };
class B : public A { };
class C : public B { };

3.Multiple Inheritance

class A { };
class B { };
class C : public A, public B { };

4.Hierarchical Inheritance

class A { };
class B : public A { };
class C : public A { };

5.Hybrid Inheritance (a combination of multiple types)

Access Specifiers in Inheritance

Base Class Access public Inheritance protected Inheritance private Inheritance


public Public Protected private
protected protected Protected private
private Not inherited Not inherited Not inherited

Public:

Members declared as public are accessible from anywhere in the program both inside and outside the
class.
They form the public interface of the class allowing other parts of the code to interact with the
object.

class MyClass {
public:
int publicVar;
void publicMethod() { /* ... */ }
};

Private:

Members declared as private are only accessible within the class in which they are declared.
They can’t be accessed directly from outside the class even by objects of the same class
class MyClass {
private:
int privateVar;
void privateMethod() { /* ... */ }
};

Protected:

Members declared as protected are accessible within the class itself and by derived class.
They are not accessible from outside the class non drive classes or standalone classes.
class BaseClass {
protected:
int protectedVar;
};

class DerivedClass : public BaseClass {


public:
void accessProtected() {
protectedVar = 10; // Accessible in derived class
}
};

Single Inheritance

Single inheritance means a derived class inherits from a single base class. The derived class gets
all the properties (data members) and behaviors (member functions) of the base class, and it can also
have its own members.

Syntax:

class Base {
public:
void display() {
std::cout << "Display from Base class" << std::endl;
}
};

class Derived : public Base { // Derived class inherits from Base class
public:
void show() {
std::cout << "Show from Derived class" << std::endl;
}
};

Example:

#include <iostream>
class Base {
public:
void display() {
cout << "Display from Base class" << endl;
}
};
class Derived : public Base {
public:
void show() {
cout << "Show from Derived class" << endl;
}
};
int main() {
Derived obj;
obj.display(); // inherited from Base class
obj.show(); // own member function
return 0;
}

Multilevel Inheritance

In multilevel inheritance, a class is derived from a class which is also derived from another
class. So, inheritance happens in a chain.

Syntax:

Base Class → Derived Class 1 → Derived Class 2

Example:

#include <iostream>
// Base class
class Animal {
public:
void eat() {
cout << "I can eat." << endl;
}
};
// Derived class 1
class Dog : public Animal {
public:
void bark() {
cout << "I can bark." << endl;
}
};
// Derived class 2 (derived from Dog)
class Puppy : public Dog {
public:
void weep() {
cout << "I can weep." << endl;
}
};
int main() {
Puppy p;
p.eat(); // inherited from Animal
p.bark(); // inherited from Dog
p.weep(); // own method
return 0;
}

Multiple Inheritance
Multiple inheritance means a class can inherit from more than one base class. This allows a
derived class to combine the features (methods and attributes) of multiple classes.
Syntax
class Base1 {
public:
void show() {
std::cout << "Base1 show()" << std::endl;
}
};

class Base2 {
public:
void display() {
std::cout << "Base2 display()" << std::endl;
}
};

class Derived : public Base1, public Base2 {


// Derived inherits from both Base1 and Base2
};

Example:

#include <iostream>
class Base1 {
public:
void show() {
cout << "Base1 show()" << endl;
}
};
class Base2 {
public:
void display() {
cout << "Base2 display()" << endl;
}
};
class Derived : public Base1, public Base2 {
public:
void hello() {
cout << "Derived hello()" << endl;
}
};

int main() {
Derived obj;
obj.show(); // from Base1
obj.display(); // from Base2
obj.hello(); // from Derived
return 0;
}

Output:

Base1 show()
Base2 display()
Derived hello()

Hierarchical inheritance

Hierarchical inheritance in C++ involves a single base class with multiple derived classes
inheriting from it. This creates a tree-like structure where the base class serves as the root, and the
derived classes branch out.
Features:

 Single Base Class: A single class acts as the parent or superclass.


 Multiple Derived Classes: Several classes inherit from the same base class.
 Code Reusability: Derived classes inherit properties and methods from the base class,
promoting code reuse.
 Modularity: Each derived class can have its own unique features, extending the functionality of the
base class.

#include <iostream>
class Animal {
public:
void eat() {
std::cout << "This animal eats food." << std::endl;
}
};
class Dog : public Animal {
public:
void bark() {
std::cout << "Dog barks." << std::endl;
}
};
class Cat : public Animal {
public:
void meow() {
std::cout << "Cat meows." << std::endl;
}
};
int main() {
Dog dog1;
std::cout << "Dog Class:" << std::endl;
dog1.eat();
dog1.bark();
Cat cat1;
std::cout << "\nCat Class:" << std::endl;
cat1.eat();
cat1.meow();
return 0;
}

Hybrid Inheritance

Hybrid inheritance in C++ is a combination of multiple inheritance types, such as single,


multiple, and multilevel inheritance. It allows a class to inherit from multiple base classes and create
a complex class hierarchy.

Characteristics:
 Combination of Inheritance Types:
It involves using more than one type of inheritance in a single class hierarchy.
 Flexibility:
It provides a flexible way to structure classes by combining different inheritance approaches.
 Code Reusability:
It allows for code reuse by inheriting properties and behaviors from multiple sources.

Example:

class A {
public:
void displayA() {
cout << "Class A" << endl;
}
};
class B : public A {
public:
void displayB() {
cout << "Class B" << endl;
}
};

class C {
public:
void displayC() {
cout << "Class C" << endl;
}
};

class D : public B, public C {


public:
void displayD() {
cout << "Class D" << endl;
}
};
int main() {
D obj;
obj.displayA(); // Inherited from A through B
obj.displayB(); // Inherited from B
obj.displayC(); // Inherited from C
obj.displayD(); // From class D
return 0;
}

Multipath Inheritance

Multipath Inheritance in C++ is derivation of a class from other derived classes, which are
derived from the same base class.This type of inheritance involves other inheritance like multiple,
multilevel, hierarchical etc.
#include <iostream>
#include <conio>
class person
{
public:
char name[100];
int code;
void input()
{
cout<<"\nEnter the name of the person : ";
cin>>name;
cout<<endl<<"Enter the code of the person : ";
cin>>code;
}
void display()
{
cout<<endl<<"Name of the person : "<<name;
cout<<endl<<"Code of the person : "<<code;
}
};
class account:virtual public person
{
public:
float pay;
void getpay()
{
cout<<endl<<"Enter the pay : ";
cin>>pay;

}
void display()
{
cout<<endl<<"Pay : "<<pay;
}
};
class admin:virtual public person
{
public:
int experience;
void getexp()
{
cout<<endl<<"Enter the experience : ";
cin>>experience;
}
void display()
{
cout<<endl<<"Experience : "<<experience;
}};
class master:public account,public admin
{
public:
char n[100];
void gettotal()
{
cout<<endl<<"Enter the company name : ";
cin>>n;
}
void display()
{
cout<<endl<<"Company name : "<<n;
}
};
int main()
{
master m1;
m1.input();
m1.getpay();
m1.getexp();
m1.gettotal();
m1.person::display();
m1.account::display();
m1.admin::display();
m1.display();
return 0;
}
Virtual Base Class

A virtual base class is a concept from object-oriented programming in C++ that helps solve the
diamond problem when using multiple inheritance.
Characteristics
1. Avoids Duplicate Inheritance: A virtual base class ensures that only one instance of the base
class is shared among all derived classes, preventing duplication.
2. Used in Multiple Inheritance: It is particularly useful when a class is indirectly inherited
multiple times through different paths.
3. Declared with virtual Keyword: The base class is declared as virtual in the inheritance
declaration.

Imagine the following inheritance hierarchy:


class A {
public:
void show() { std::cout << "A::show" << std::endl; }
};

class B : public A { };
class C : public A { };
class D : public B, public C { };

Here, D inherits from both B and C, and both B and C inherit from A. So, D ends up with
two copies of A, one from B and one from C. This causes ambiguity when trying to call a
method from A:

D obj;
obj.show(); // Error: ambiguous

To avoid this, you can declare A as a virtual base class when inherited:

class A {
public:
void show() { std::cout << "A::show" << std::endl; }
};
class B : virtual public A { };
class C : virtual public A { };
class D : public B, public C { };

Now, D has only one shared copy of A, and the ambiguity is resolved.

D obj;
obj.show(); // Works fine, calls A::show

Abstract Class

In C++, an abstract class is a class that cannot be instantiated directly. It serves as a blueprint
for other classes to inherit from. The key characteristic of an abstract class is that it contains at
least one pure virtual function.

Features:

 Pure Virtual Functions:


A pure virtual function is declared using the syntax = 0 after the function declaration. For
example: virtual void draw() = 0;. This indicates that the function has no implementation in the
abstract class and must be overridden by derived classes.
 Cannot be Instantiated:
You cannot create objects of an abstract class directly. Attempting to do so will result in a
compilation error.
 Base Class:
Abstract classes are designed to be base classes, providing a common interface for derived
classes to implement. They define a contract that derived classes must adhere to.

 Polymorphism:
Abstract classes are essential for achieving polymorphism in C++. You can use pointers or
references to an abstract class to refer to objects of its derived classes.
 Derived Class Responsibility:

Derived classes must implement all pure virtual functions of the abstract class. If a derived
class fails to implement a pure virtual function, it also becomes an abstract class.

// C++ program to calculate the area of a square and a circle

#include <iostream>
using namespace std;
// Abstract class
class Shape {
protected:
float dimension;
public:
void getDimension() {
cin >> dimension;
}
// pure virtual Function
virtual float calculateArea() = 0;
};
// Derived class
class Square : public Shape {
public:
float calculateArea() {
return dimension * dimension;
}
};
// Derived class
class Circle : public Shape {
public:
float calculateArea() {
return 3.14 * dimension * dimension;
}
};
int main() {
Square square;
Circle circle;
cout << "Enter the length of the square: ";
square.getDimension();
cout << "Area of square: " << square.calculateArea() << endl;
cout << "\nEnter radius of the circle: ";
circle.getDimension();
cout << "Area of circle: " << circle.calculateArea() << endl;
return 0;}

QUESTIONS

UNIT -III

Multiple Choice Questions (MCQs)

1).Which of the following operators can be overloaded in C++?


a) sizeof
b) ::
c) +
d) ?:
Answer: c) +

2).What is the main purpose of a virtual base class?


a) Increase speed
b) Resolve ambiguity in multiple inheritance
c) Use operator overloading
d) Avoid abstraction
Ans: b) Resolve ambiguity in multiple inheritance

3). Which type of inheritance involves more than one base class?
a) Single
b) Multilevel
c) Multiple
d) Hierarchical
Ans: c) Multiple
4). In operator overloading, which function is not a member function?
a) Constructor
b) Friend function
c) Destructor
d) Inline function
Ans: b) Friend function
5).Inheritance in C++ provides:
a) Function Overloading
b) Reusability
c) Data hiding
d) Encapsulation
Ans: b) Reusability
6).A class having at least one pure virtual function is called:
a) Static class
b) Virtual class
c) Abstract class
d) Friend class
Ans: c) Abstract class
2.Fill in the blanks
7).Operator overloading is a type of _______.
Ans: Polymorphism
8). A class containing at least one pure virtual function is called an _______ class.
Ans: Abstract
9). In C++, type conversion can be categorized as basic to class, class to basic, and _______.
Ans: Class to class
10). A _______ function can access private data of a class without being a member of the class.
Ans: Friend
11).In multiple inheritance, ambiguity can be resolved using _______ base classes.
Ans: Virtual
12). _______ inheritance is a combination of more than one type of inheritance.
Ans: Hybrid
2 Mark Questions
1. Define operator overloading.
2. What is the difference between unary and binary operators?
3. Write a syntax for overloading a binary operator using a friend function.
4. What is type conversion?
5. Define single inheritance.
6. What is a virtual base class?
7. Define an abstract class with an example.
8. What is hybrid inheritance?
9. Why can't we overload the scope resolution operator (::)?
10. What is the difference between multiple and multilevel inheritance?

5 Mark Questions
1. Explain the concept of operator overloading with an example.
2. Describe how binary operator overloading using friend functions.
3. What is type conversion? Explain different types of type conversion in C++.
4. Compare single and multiple inheritance with examples.
5. Explain virtual base classes with suitable examples.
6. What is an abstract class? How is it different from a concrete class?
7. What are the limitations of operator overloading in C++? List the operators that cannot be
overloaded.

10 Mark Questions
1. Write a C++ program to overload the binary '+' operator using:
o Member function

o Friend function

2. Discuss various types of inheritance in C++ with diagrams and examples.


3. What is type conversion? Explain the following
o Basic to class

o Class to basic

o Class to class conversions with examples.

4. Explain the concept of Hierarchical inheritance with example.


5. What is an abstract class? Explain its role in implementing polymorphism with examples.
6. Write a C++ program to demonstrate the concept of abstract classes and pure virtual functions.
UNIT-IV

Pointers – Declaration – Pointer to class, object – This pointer – Pointers to derived classes and base
classes – Arrays – Characteristics – Array of classes – Memory models – new and delete operators –
Dynamic objects – Binding, Polymorphism, and Virtual Functions.

Pointers
In C++,a pointer is a variable that stores the memory address of another variable.

Declaration:
Syntax:

data_type *pointer_name;

data_type: Specifies the type of variable the pointer will point to


(e.g., int, char, float, double, or a custom class).
*:The asterisk symbol indicates that the variable is a pointer.
pointer_name:The name of the pointer variable.

int *ptr_int; // Pointer to an integer


char *ptr_char; //Pointer to a character
double*ptr_double;//Pointer to a double

Initialization

Pointers can be initialized in several ways: Pointing to an existing variable.

int num = 10;


int *ptr=&num;// ptr now holds the address of num

The & operator(address-of operator) retrieves the memory address of the variable num.
Using nullptr
int *ptr=nullptr;//A null pointer, it does not point to any memory
Null ptr is used to indicate that the pointer does not currently point to a valid
memory location.

Dynamic memory allocation


int *ptr=new int;//Allocates memory for an integer and ptr holds the address of the memory.

The new operator allocates memory during runtime.

Using pointers
To access the values at the memory address pointed to by a pointer, the dereference operator
* is used
int num=10;
int *ptr= &num;
std::cout<<*ptr;//Output:10(value of num)
*ptr=20;//Modifies the value of num
std::cout << num; // Output: 20

Example:

#include <iostream>
int main() {
int var = 10; // Declare and initialize an
integer variable
int* ptr; // Declare a pointer to an
integer
// Assign the address of 'var' to 'ptr'
ptr = &var;
std::cout << "Value of var: " << var <<
std::endl;
std::cout << "Address of var (&var): "
<< &var << std::endl;
std::cout << "Value stored in ptr
(address of var): " << ptr << std::endl;
std::cout << "Value pointed to by ptr
(*ptr): " << *ptr << std::endl;
// Change the value of 'var' using the
pointer
*ptr = 20;
std::cout << "\nAfter changing value
through pointer:" << std::endl;
std::cout << "Value of var: " << var <<
std::endl;
std::cout << "Value pointed to by ptr
(*ptr): " << *ptr << std::endl;
return 0;
}
C++ Classes and Objects

In C++, classes and objects are the basic building block that leads to Object-Oriented
programming in C++.

C++ Classes
A class is a user-defined data type, which holds its own data members and member
functions that can be accessed and used by creating an instance of that class. A C++classis like a
blueprint for an object.
For Example: Consider the Class of Cars. There may be many cars with different names
and brands but all of them will share some common properties like all of them will have 4
wheels, Speed Limit, Mile age range, etc. The car can also accelerate, turn, apply brakes, etc. So
here, the Car is the class, wheels, speed limits, and mileage are its attributes (data members) and
accelerate, turn, apply brakes are its methods (member functions).

Create a Class
A class must be defined before its use. C++ class is defined using the keyword class keyword as
shown:
Class className{
access_specifier:

//data member

//member method
};

 Data Members: These are the variables that are defined inside the class.
 Member Functions: Functions declared inside a class. Also referred to as a member
method.

#include<iostream.h>
//Creating a class
class GfG {
public:
//Data member
int val;
//Member function
void show() {
cout<<"Value:"<<val<<endl;
}
};
int main(){
//Create Object
GfGobj;
//Access data member and assign
//its me value
obj.val = 10;
//Access member method
obj.show();
return0;
}

C++ Objects
C++ objects are instances of classes, which are user-defined data types that serve as
blueprints for creating objects. Objects encapsulate data (attributes) and functions(methods) that
operate on that data.

Features

 Classes as Blueprints: A class defines the structure and behavior of objects. It's a
template for creating objects.
 Objects as Instances : An object is a specific instance of a class. It's a concrete
entity created based on the class blueprint.
 Encapsulation: Objects bundle data and functions together, hiding internal details
and exposing only necessary interfaces.
 Data Members: Attributes or variables that store the state of an object.
 Member Functions: Methods that define the behavior of an object.
 Creation: Objects are created using the class name followed by the object name.
 Access : Object members are accessed using the dot operator (.).

Syntax:
Class Dog{
public:
std::string name;
int age;

void bark(){
std::cout<<"Woof!"<<std::endl;
}

};

int main(){
Dog myDog;// Create an object of the Dogclass
myDog.name="Buddy";
myDog.age = 3;
myDog.bark();//Call the bark method
return 0;
}

This pointer
The this pointer in C++ is an implicit pointer available within non-static member
functions of a class, struct, or union. It points to the object for which the member function is
called.
Characteristics:
 Implicit:
It's automatically passed as a hidden argument to non-static member functions.
 Object Reference:
This always refers to the specific instance of the class that invoked the function.
 Non-Modifiable:
The address held by this remains constant throughout the object's lifetime.

#include <iostream>
using namespace std;
class Student {
int age;
public:
Student(int age) {

// "this->age" refers to the data member


this->age = age;
}

// Function to display age


void display() const {
cout << "Age: " << this->age << endl;
}
};
int main() {
Student s1(20);
s1.display();
return 0;
}

Pointers to derived classes and base classes


In C++ (and many object-oriented languages), pointers to base and derived classes are
used to achieve polymorphism, code reusability, and flexible interface design.
Features
1. Base Class Pointer to Derived Class Object(Upcasting)

This is allowed implicitly. It enables polymorphism, letting you call overridden methods
in the derived class through a base class pointer, provided the base class function is virtual.

classBase{ p
ublic:
virtualvoidshow() {
std::cout <<"Baseclass\n";
}
};
classDerived:publicBase{ pu
blic:
voidshow()override{
std::cout<<"Derivedclass\n";
}
};
int main()
{ Derived;
Base *ptr=&d;//Baseclass pointer to derived classobject
ptr->show(); //Output:Derived class(due to virtual function)}

2.Derived Class Pointer to Base Class Object(Downcasting)


This is not allowed implicitly, and must be done carefully(often using dynamic_cast with
polymorphic types).

Base *base=newBase();
Derived* derived = dynamic_cast<Derived*>(base);// This will return nullptr if cast is
invalid.

You can only safely down cast if the object is actually of the derived type.

Arrays in C++
Arrays in C++ are a fundamental data structure used to store a fixed-size sequence of
elements of the same data type.
Declaring an Array
type arrayName[arraySize];
int numbers[5];//Declaresanarrayof5 integers
Initializing an Array
You can initialize arrays at the time of declaration:
Int numbers[5]={1, 2,3,4, 5};

Or partially initialize:
int numbers[5]={1,2};//Remaining elements are set to 0

You can also let the compiler determine the size:


int numbers[]={1,2, 3};//Sizeis3

Accessing Array Elements


Array elements are accessed using indices(startingat0):
cout << numbers[0];// Outputs first element
numbers[2] = 10; //Setsthirdelementto10

Example:

#include <iostream> // Required for


input/output operations

int main() {
// Declare and initialize an integer array
int numbers[5] = {10, 20, 30, 40, 50};

// Access and print individual elements


std::cout << "Element at index 0: " <<
numbers[0] << std::endl;
std::cout << "Element at index 2: " <<
numbers[2] << std::endl;

// Modify an element
numbers[1] = 25;
std::cout << "Modified element at index 1:
" << numbers[1] << std::endl;

// Iterate through the array using a for loop


std::cout << "\nAll elements in the array:"
<< std::endl;
for (int i = 0; i < 5; ++i) {
std::cout << "numbers[" << i << "] = "
<< numbers[i] << std::endl;
}
// Declare an array and take user input to
populate it
int user_input_array[3];
std::cout << "\nEnter 3 numbers for
another array:" << std::endl;
for (int i = 0; i < 3; ++i) {
std::cout << "Enter number " << (i + 1)
<< ": ";
std::cin >> user_input_array[i];
}
// Print the elements of the user-populated
array
std::cout << "\nNumbers entered by user:"
<< std::endl;
for (int i = 0; i < 3; ++i) {
std::cout << user_input_array[i] << " ";
}
std::cout << std::endl;

return 0; // Indicate successful execution


}

Characteristics of an array

In C++, an array is a data structure that holds a fixed-size sequence of elements of the same data
type. Here are the key characteristics of arrays in C++:

1. Homogeneous Elements
1. All elements must be of the same data type(e.g.,all int,all float).
2. Float prices[3];//All elements are of float type
2. Contiguous Memory Allocation
1. Array elements are stored in continuous memory locations, making access
via index fast.
3. Zero-Based Indexing
1. Theindexofthefirstelementis0, and the last is size- 1.
2. arr[0]=10;// First element
3. arr[4]=50;//Lastelementina5-elementarray
4. Direct Access via Index
1. Any element can be accessed directly using its index.
2. int x=arr[2];//Accessing the3rd element

5. Uninitialized Values
1. If not explicitly initialized, array elements may contain garbage values(for local
arrays).
2. int arr[3];//Contains indeterminate values if not initialized
6. Static vs Dynamic Arrays
Static arrays are declared with a fixed size:
int arr[10];//Static array
Dynamic arrays are created using pointers and new:
int*arr= new int[n];// Dynamic array of size n

Array of classes
In C++, an array of classes, also referred to as an array of objects, is a collection of
instances of the same class type stored contiguously in memory. This allows for the management
and manipulation of multiple objects with similar properties and behaviors using a single data
structure.

Declaration and Initialization:


Similar to arrays of fundamental data types, an array of objects is declared by specifying the
class name, followed by the array name and its size within square brackets.

ClassName arrayName[size];
For example, to declare an array of Employee objects named employees with a sizeof10:

Employee employees[10];

When an array of objects is declared, the default constructor of the class is called
for each object in the array. If a class does not have a default constructor, or if you need
to initialize objects with specific values, you can use an initializer list or a loop to call
parameterized constructors or set member variables after creation.

//Using an initialize list(requires default constructor or aggregate initialization)

ClassName arrayName[size] = { object1_initializer, object2_initializer, ... };

// Example with a custom class

Class MyClass{
public:
Int value;
MyClass(intval=0):value(val){}//Defaultconstructorandparameterized constructor
};
MyClassobjects[3]={MyClass(10),MyClass(20),MyClass()};//Initializeswith specific
values and default

Accessing Elements:
Individual objects within the array are accessed using their index,starting from0.
arrayName[index].memberVariable;
arrayName[index].memberFunction();
For instance,to access the name member of the first Employee object in
the employees array:employees[0].name;

Advantages:
1. Centralized Management: Allows for efficient handling of multiple related objects.
2. Structured Data: Provides a clear and organized way to store collections of objects.
3. Iteration: Easily traversed using loops to perform operations on all objects within the array.

C++ Memory Model


The C++ memory model defines how a C++ program interacts with memory, particularly
in concurrent, multithreaded environments. It addresses challenges related to data races,
instruction reordering, and ensuring consistent visibility of shared data across threads.

Key aspects of the C++ memory model:

Sequential Consistency:
This is the strongest and most intuitive memory ordering, where all operations appear to
execute in a single, global order consistent with the program order within each thread

Relaxed Memory Orderings:


To enable better performance,C++ offers weaker memory orderings for atomic operations
(e.g., std::memory_order_relaxed, std::memory_order_acquire, std::memory_order_release, std
::memory_order_acq_rel)

Atomic Operations:
The std::atomic template provides primitives for performing operations on shared
variables in a thread-safe manner, preventing data races. These operations can be explicitly
given a memory ordering to control their synchronization behavior.

Synchronization Primitives:
The memory model works in conjunction with other synchronization mechanisms like
mutexes (std::mutex), condition variables (std::condition_variable), and locks, which establish
synchronization points and ensure memory visibility.

Happens-Before Relationship:
This fundamental concept defines a partial ordering of operations, ensuring that if operation
A happens-before operation B, then the effects of A are visible to B.
Data Races:
The C++ memory model defines what constitutes a data race (concurrent,
unsynchronized access to shared mutable data) and specifies that programs with data races
have undefined behavior, meaning the outcome is unpredictable.
new and delete operators
In C++, the new and delete operators are fundamental for managing dynamic memory
allocation on the heap (also known as the free store). They provide a mechanism for programs to
request and release memory during runtime, which is particularly useful when the required
memory size is not known at compile time or when dealing with dynamic data structures.
The new operator:
Purpose:The new operator is used to dynamically allocate memory for a single object or
an array of objects on the heap.

Syntax
pointer_variable = new data_type; // For a single object

pointer_variable= newdata_type[size];//For an array of objects

Functionality:
1. It allocates the specified amount of memory from the heap.
2. If allocating for an object, it calls the object's constructor (if one exists) to initialize it.
3. It returns a pointer to the beginning of the newly allocated memory block.
4. If memory allocation fails(e.g.,due to insufficient memory), new throws
a std::bad_alloc exception by default

The delete Operator:


Purpose: The delete operator is used to deallocate memory that was previously allocated using
the new operator, returning it to the free store.
Syntax:
delete pointer_variable; // For a single object
delete[]pointer_variable;//For an array of objects

Example:

#include <iostream>
#include <memory>
using namespace std;
int main() {

// Declared a pointer to store


// the address of the allocated memory
int *nptr;

// Allocate and initialize memory


nptr = new int(6);
// Print the value
cout << *nptr << endl;
// Print the address of memory
// block
cout << nptr;
return 0;
}

Functionality

If deallocating an object, it calls the object's destructor(if one exists) before freeing the
memory.
It releases the memory pointed to by pointer_variable, making it available for
future allocations.
Crucial Note: Using delete on memory not allocated with new, or using the wrong form
(e.g., delete on an array allocated with new[]), leads to undefined behavior and potential
memory corruption.

Dynamic objects in C++

In C++,dynamic objects are instances of class created at runtime, rather than at compile time. This
means their memory is allocated on the hep not the stack and their lifetime.is not tied to the scope in
which they are created. This provides flexibility in managing object lifetimes and memory usage.

Key characteristics of dynamic objects:

Runtime Creation:
Dynamic objects are created during program execution, allowing for flexible memory
management based on program needs or user input.

Heap Allocation:
Unlike static or stack-allocated objects, dynamic objects reside in the heap memory, a region
of memory available for dynamic allocation.

Pointer-Based Access:
When a dynamic object is created using new, it returns a pointer to the newly allocated memory
location. This pointer is then used to access the object's members (data and functions) using the
arrow operator (->).
Explicit Memory Management:
Programmers are responsible for explicitly deallocating the memory occupied by dynamic
objects using the delete operator when they are no longer needed. Failure to do so leads to
memory leaks.

Constructor and Destructor Calls:


When a dynamic object is created, its constructor is called, and when it's deleted, its destructor
is called, ensuring proper initialization and cleanup.

Polymorphism in C++

Polymorphism, meaning "many forms," is a fundamental concept in C++ object-oriented


programming that allows a single interface to represent different underlying forms or behaviors.
1. Compile-time Polymorphism(Static Polymorphism):

This type of polymorphism is resolved during the compilation phase. The compiler
determines which function or operator to call based on the arguments' types and number.

Function Overloading: Allows multiple functions with the same name but different
parameters(number or type of arguments). The compiler selects the appropriate function based
on the arguments provided during the call.
Operator Overloading: Allows operators (like +, -, *, /) to be redefined for custom
classes. This is provides a more intuitive way to perform operations on user-defined types.
2. Run-time Polymorphism(Dynamic Polymorphism):

This type of polymorphism is resolved during program execution. It relies on inheritance


and virtual functions.

Virtual Functions:
Declared in a base class using the virtual keyword and overridden in derived classes. When a
base class pointer or reference points to a derived class object, calling a virtual function through
that pointer/reference will invoke the derived class's version of the function.
This is achieved through a mechanism called the "virtual table"(vtable).

#include <iostream>
Class Shape{
public:
virtual voiddraw() {
std::cout<<"Drawing a generic shape."<<std::endl;
}};
Class Circle:public Shape
{ public:
void draw()override{//'override'keyword is good practice std::cout <<"Drawing a circle."<< std::endl;
}
};
Class Square:public Shape{ public:
void draw() override{
std::cout<<"Drawing a square."<<std::endl;
}
};
int main(){
Shape* s1 = new Circle(); Shape*s2=new Square();
s1->draw(); // Calls Circle's draw() s2->draw();//Calls Square's draw() delete s1;
delete s2;
return 0;}

Questions

Multiple choice questions

1) Which operator is used to get the address of a variable?


a) *
b) &
c) ->
d) %
Ans: b) &

2) The pointer that points to the calling object in a class is called:


a) self pointer
b) this pointer
c) base pointer
d) obj pointer
Ans: b) this pointer

3) Which operator is used to access members of a class through a pointer?


a) .
b) ->
c) *
d) &
Ans: b) ->

4) Which operator is used to allocate memory dynamically in C++?


a) malloc
b) new
c) create
d) alloc
Ans: b) new

5) Which operator is used to deallocate memory allocated dynamically?


a) free()
b) delete
c) dispose
d) remove
Ans: b) delete

6) Polymorphism in C++ can be achieved by:


a) Function overloading
b) Virtual functions
c) Inheritance
d) All of the above
Ans: d) All of the above

7) Which type of binding occurs at compile time?


a) Early binding
b) Late binding
c) Dynamic binding
d) Virtual binding
Ans: a) Early binding

8) Which type of binding occurs at runtime?


a) Static binding
b) Dynamic binding
c) Compile-time binding
d) Reference binding
Ans: b) Dynamic binding
9) An array of objects in C++ is used to:
a) Store multiple objects of the same class
b) Store different classes
c) Store pointers
d) Store functions
Ans: a) Store multiple objects of the same class

10) A pointer to derived class can be assigned to a pointer to base class:


a) True
b) False
Ans: a) True

Fill in the blanks

1) The keyword used to allocate memory dynamically is new.


2) The keyword used to free dynamic memory is delete.
3) Pointer to an object is declared as ClassName* ptr;
4) The pointer that refers to the calling object is called this pointer.
5) Array elements are stored in contiguous memory locations.
6) Polymorphism allows objects to behave differently for the same function call.
7) Virtual functions support runtime polymorphism.
8) Binding refers to associating a function call with a function definition.
9) The operator used to access members via pointer is ->.
10) Dynamic objects are created in the heap memory.

Two mark questions

1) What is a pointer to a class object?


2) What is the purpose of the this pointer?
3) List the types of memory allocation in C++.
4) What is an array of objects?
5) Differentiate early binding and late binding.

Five mark questions

1) Explain pointer to class object and how members are accessed using pointers.
2) Explain this pointer with an example.
3) Write short notes on arrays in C++ and array of objects with an example.
4) What are the characteristics of arrays in C++.
5) Explain dynamic memory allocation using new and delete operators with examples.

Ten mark questions

1) Explain the concept of binding and differentiate between early and late binding.
2) Write a program to demonstrate dynamic binding using virtual functions.
3) Explain pointers to derived classes and base classes with an example.
V UNIT

Files – File stream classes – File modes – Sequential Read/Write operations– Binary and ASCII
files – Random access operation – Templates –Exception handling – String – Declaring and
initializing string objects –String attributes – Miscellaneous functions

Files

Files:

File handling in C++ allows programs to interact with external files for persistent data storage.

Key Classes for File Handling:

ofstream: Used for writing data to files. It represents an output file stream.
ifstream: Used for reading data from files. It represents an input filestream.
fstream: Can be used for both reading from and writing to files. It represents a
general file stream.

File Handling in C++


In C++, input and output are done in the form of a sequence of bytes called streams.
For example, cin and cout are the objects associated with the standard input and output
streams.
These streams are represented by different classes provided in the
&lt;iostream&gt;library. Similarly, C++ also provides file stream classes to perform
input and output operations on files that are defined inside &lt;fstream&gt; header
file.

File Handling Operations

There are mainly three main steps in file handling:


1. Opening a File
2. Read/Write Operations
3. Closing a File

Opening a File
Beforer reading from or writing to a file, we first need to open it. Opening a file loads
that file in the RAM. In C++, we open a file by creating a stream to it using the
fstream class that represent the file stream i.e. stream for input and output to the file.
1. str:Name given to the stream
2. filename: Name of the file
3. mode:Represents the way in which we are going to interact with the file

#include <fstream>
#include <iostream>
int main() {
std::ifstream inputFile;
inputFile.open("another_example.txt"); // Open for reading
std::ofstream outputFile;
outputFile.open("another_output.txt", std::ios::out | std::ios::app); // Open for
appending

if (inputFile.is_open()) {
std::cout << "another_example.txt opened successfully." << std::endl;
} else {
std::cout << "Failed to open another_example.txt." << std::endl;
}
// ... perform file operations ...
inputFile.close();
outputFile.close();
return 0;
}

File Opening Modes


File opening mode indicate file is opened for reading, writing, or appending. Below is
the list of all file modes in C++:
Mode Description
ios::in File open for reading. If file does not exists,
ios::out File open for writing: the internal stream buffer supports output operations.
ios::binary Operations are performed in binary mode rather than text.
ios::ate The output position starts at the end of the file.
ios::appAll outpu operations happen at the end of the file, appending to its
existing contents.
ios::trunc Any contents that existed in the file before it is open are discarded.

For Example, if we want to open the file for reading, we use the following opening
mode: fstream filein(&quot;file.txt&quot;, ios::in);
Similarly, if we want to open the file for writing, we use the
following: fstream fileout(&quot;file.txt&quot;, ios::out);
Other File Streams
fstream is not the only file stream provided by C++.There are two more specialized streams:

1. ifstream:Stands for input filestream. It is equivalent to open fstream in ios::in mode.


2. ofstream:Stands for output filestream.It is equivalent to opening fstream in
ios::out mode.

File Stream Classes


1. In C++,file streams are used for input and output operations on files.
2. The standard filestream classes are part of &lt;fstream&gt;header.
3. The main classes for file stream handling in C++ are iffstream,ofstream,and
4. fstream.

The following Figure shows the filestream class hierarchy.

Sequential Read/Write operations


In C++, sequential read and write operations on files involve processing data in a
specific order, typically from the beginning of the file to the end, or from the current
position of the file pointer. This contrasts with random access, where specific locations
within a file can be directly accessed.
Sequential Read/Write Operations:
To write data sequentially to a file in C++,the ofstream class is used.

1. Include Header: Include the<fstream>header.


2. Create ofstreamObject: Instantiate an ofstreamobject, optionally providing the
filename and open mode (e.g., ios::app for appending, ios::trunc for
overwriting).
3. Check for Errors: Verify that the file opened successfully using
is_open()orby checking the stream object directly (e.g., if (!fout)).
4. Write Data:Use the insertion operator(<<)to write data to the file,similar to cout.
5. Close File:Close the file usingthe close() member function.
6. Sequential Read Operations:

To read data sequentially from a file,the ifstream classis employed.

1. Include Header: Include the<fstream>header.


2. Create ifstream Object:Instantiate an ifstream object,providing the filename
and open mode (e.g., ios::in for reading).
3. Check for Errors:Verify that the file opened successfully.
4. ReadData:Use the extraction operator(>>)to read data into
variables,orgetline() for reading entire lines.
5. Close File:Close the file using the close()member function.

#include < iostream > // Required for input & output


#include < fstream > // Required for file operations
int main() {
// Create a new file in write mode
fstream myFile;
cout << "WRITING PURPOSE:" << endl;
myFile.open("InfoBrother.txt", ios::out); // Open file for writing

if (!myFile) { // Check for errors if file didn't open


cout << "Error while opening file." << endl;
} else {
cout << "New file opened successfully for writing." << endl; }

myFile.close(); // Close the file


if (!myFile.is_open()) { // Check if file is closed
cout << "File has been closed." << endl;
} else {
cout << "File is still open." << endl;
}
// Open an existing file for reading and appending
cout << "\n\nREADING & APPENDING PURPOSE:" << endl;
myFile.open("InfoBrother.txt", ios::in | ios::app);

if (!myFile) {
cout << "Error while opening file." << endl;
} else {
cout << "Existing file opened successfully for reading & appending." << endl;
}

// Let's not close the file and check for errors


if (!myFile.is_open()) {
cout << "File has been closed." << endl;
} else {
cout << "File is still open." << endl;
}

return 0;}

Binary and ASCII Files

In C++, files can be broadly categorized into two types based on how data is stored and
interpreted: ASCII (or text) files and binary files.

ASCII(Text)Files:
1. Nature:

These files store data as a sequence of characters, typically using the ASCII
encoding scheme. Each character, including numbers and symbols, is represented
by its corresponding ASCII code.

2. Human Readability:

They are human-readable and can be opened and edited with standard text editors
(e.g., Notepad, VS Code).

3. Structure:

Data is often organized into lines, with a newline character (\n) signifying the end
of a line.
4. Storage:

Numbers are converted to their string representations before being written to the
file (e.g., the integer 123 is stored as the characters '1', '2', '3').

5. Usage:
Commonly used for storing configurations, log files, source code, and any data
intended for human inspection or simple text processing.
BinaryFiles:

6. Nature:

These files store data in its raw, internal binary representation, exactly as it is
stored in memory. There is no conversion to character strings.

7. Human Readability:

They are generally not human-readable when opened with a text editor, as the
raw binary data will appear as a jumble of uninterpretable characters or
symbols.Specializedhexeditorsarerequiredtoviewtheircontentsmeaningfully.

8. Structure:

Data is stored as a continuous stream of bytes, without inherent line


breaks or character-based organization.

9. Storage:
Numbers are stored directly in their binary format (e.g., the integer 123 is stored
as its binary equivalent, which takes up 4 bytes for an int on most systems).

10. Usage:
Ideal for storing large amounts of numerical data, images, audio, executable
programs, and other data where efficiency, compactness, and direct memory
representation are important.

Random access operations in C++

Random access operations in C++ refer to the ability to directly access and manipulate
data at any arbitrary position within a data structure or file, without needing to process
preceding data sequentially.

1. seekg()(seekget):Used with input filestreams(ifstream) to reposition


the"get"pointer (for reading).
2. seekp()(seekput):Used with output filestreams(ofstream )to reposition
the"put" pointer (for writing).
3. tellg() an dtellp():These functions return the current position of the get and put
pointers, respectively.
Templates in C++

Templates in C++are a powerful feature that enable generic programming, allowing


functions and classes to operate with generic types instead of specific data types.

GenericProgra
mming
Template
Parameters
TypeParameters
Non-
TypeParameters
Template Instantiation
Function Templates
Class Templates
Specialization

Example:

#include
<iostream>
// Function
template to find
the maximum of
two values
template
<typename T>
T findMax(T a,
T b) {
return (a >
b) ? a : b;
}
int main() {
// Using
findMax with
integers
int maxInt =
findMax(10, 5);
std::cout <<
"Max of 10 and
5: " << maxInt
<< std::endl;
// Using
findMax with
doubles
double
maxDouble =
findMax(3.14,
2.71);
std::cout <<
"Max of 3.14
and 2.71: " <<
maxDouble <<
std::endl;
// Using
findMax with
characters
char maxChar
= findMax('X',
'A');
std::cout <<
"Max of 'X' and
'A': " <<
maxChar <<
std::endl;
return 0;
}

Exception handling in C++


Exception handling in C++provides a structured mechanism to manage and respond to
runtime errors or exceptional conditions, preventing abnormal program termination and
allowing for graceful error recovery. It utilizes three keywords: try, throw, and catch.

1.try Block:
The try block encloses a section of code where an exception migh to ccur. If an
exceptional condition arises within this block, an exception is "thrown."

#include <iostream>
#include <stdexcept> // For standard exception classes like std::runtime_error
double divide(double numerator, double denominator) {
if (denominator == 0) {
throw std::runtime_error("Division by zero is not allowed.");
}
return numerator / denominator;
}
int main() {
try {
double result = divide(10.0, 2.0);
std::cout << "Result of division: " << result << std::endl;
result = divide(5.0, 0.0); // This will throw an exception
std::cout << "This line will not be executed." << std::endl; // Unreachable
} catch (const std::runtime_error& e) {
std::cerr << "Caught a runtime error: " << e.what() << std::endl;
} catch (...) { // Catch-all for any other unexpected exceptions
std::cerr << "Caught an unknown exception." << std::endl;
}
std::cout << "Program continues after exception handling." << std::endl;
return 0;
}
2.throw statement:
When an erroror exceptional condition is detected inside a try block, the throw statement
is used to signal the event. It creates an exception object (of any data type or a class
instance) and transfers control to a matching catch block

3.catch Block:
Immediately following a try block,one or more catch blocks are defined. Each catch
block specifies the type of exception it can handle.
#include<iostream>
#include<stdexcept>//For standard exception classes like std::runtime_error
int main(){
doubl
enumerator,denominator,result;
std::cout <<"Enter numerator: ";
std::cin >> numerator;
std::cout<<"Enterdenominator:"
; std::cin >> denominator;
try{
if(denominator==0){
throwstd::runtime_error("Division by zero is not allowed.");//Throw a standard
exception
}
result=numerator/denominator;
std::cout<<"Result:"<<result<<std::endl;
}catch(const std::runtime_error&e){//Catch the
std::runtime_errorbyreference std::cerr <<"Error: "<< e.what() <<
std::endl; // Access error message
}catch(...){//Catch-all block for any other unhandled exceptions
std::cerr <<"An unknown error occurred."<< std::endl;
}
return0;
}

Strings in C++
In C++,strings represent sequences of characters and can be handled in two primary ways
:using the std::string class and using C-style character arrays.

1. std::string Class:
The std::string class, part of the C++ Standard Library and found in the <string> header, is
the preferred and more modern way to manage strings in C++. Declaration and Initialization.
#include
<string>#include
<iostream>

int main(){
std::string s1 = "Hello"; // Direct initialization
std::string s2("World");// Constructor
initialization std::string s3; //Default
constructor,empty string s3 = "C++";
// Assignment
std::cout <<s1<<""<<s2<<""<<s3<<std::endl;
return 0;
}

2. C-style Character Arrays:


C-style strings are essentially arrays of characters terminated by a null character (\0).They are
inherited from the C language. Declaration and Initialization
#include<iostream>
#include<cstring>//Forstringmanipulationfunctionslikestrlen,strcpy

int main(){
chars1[]="Hello";//Character array,automatically
sized char s2[10]; // Fixed-size character array
strcpy(s2,"World");//Copying a string
literal std::cout << s1 <<""<< s2 <<
std::endl; return 0;}

Declaring and Initializing String objects


In C++, string objects are instances of the std::string class, which is part of the C+
+Standard Library. To use std::string, you must include the <string> header.
Declaring a std::string object:
The basic syntax for declaring a string object is:
std::string variable_name;
This declares an empty string object, meaning it contains no characters.

Initializing a std::string object:


There are several ways to initialize a std::string object:Using a string
literal(direct initialization).
std::string myString="Hello,World!";
This declares myString and initializes it with the character sequence"Hello,World!".
Usinga string literal (constructor syntax).
std::string to another String("C++Programming");
String attributes
In C++, the std::string class, which is part o f the Standard Template Library(STL),offers
a rich set of functionalities that can be considered its "attributes" or characteristics.

Key Attributes and Functionalities of std::string:

Dynamic Sizing:
length()or size():Returns the number of characters in the string.

capacity(): Returns the size of the allocated storage space, which is typically
greater than or equal to length().

resize(): Changes the number of characters in the string. max_size():


Returns the maximum possible length of the string.

Miscellaneous functions
In c++ “miscellaneous functions” refers to a collection of functions and features that do
not neatly fit into specific ,well-defined categories like arithmetic operations, string
manipulation, or input/output.

1. Operators:
size of operator:Used to determine the size in bytes of a variable or datatype.
int x;
cout<<sizeof(x)<<endl;// Prints the sizeof an int

Comma operator (,): Evaluates expressions from left to right and returns the value of the
rightmost expression. It is often used to combine multiple expressions where one is
expected.
int a=(10,20);//awillbe20
Address-ofoperator(&):Returns the memory address of a
variable. int num = 10;
cout<<&num<<endl;// Prints the memory address of num
Standard Library Functions:
1. getenv()andsetenv()
(from<cstdlib>):Functionsforinteractingwithenvironment variables.
2. rand()andsrand() (from<cstdlib>):For generating pseudo-random numbers.
3. perror()(from<cstdio>):Prints a system error message.
Array elements are accessed using indices (starting at 0):
cout << numbers[0]; // Outputs first element
numbers[2] = 10; // Sets third element to 10

Questions
Multiple choice questions

1 ) Which header file is required for file handling in C++?


a) <stream.h>
b) <fstream>
c) <file.h>
d) <iostream.h>

Ans:B
2) The class used for reading from a file is _______.
a) ofstream
b) ifstream
c) fstream
d) filebuf

Ans:B

3) Which operator is used to insert data into a file stream?


a) >>
b) <<
c) =
d) ->

Ans:B

4) Exception handling in C++ is done using ________.


a) try, catch, throw
b) if, else, endif
c) for, while, do
d) try, throw, goto

Ans: A

5) A template in C++ is used for ________.

a) Memory allocation
b) Generic programming
c) File management
d) Error handling

Ans:B

Fill in the blanks


1. The base class for file stream classes in C++ is ___________.

Ans :ios
2. The function used to open a file is ____________.

Ans : open
3. Binary files store data in __________ format.

Ans:Binary format
4. The keyword used to handle exceptions is ____________.

Ans: try
5. String objects in C++ belong to the __________ namespace.

Ans: std

Two mark questions


1) What is a file stream in C++?
2) List any two file modes used in C++.
3) Define template with an example syntax.
4) What is the purpose of try and catch blocks?
5) What is the difference between ASCII and Binary files?
Five mark questions

11) Explain the different file stream classes used in C++.


12) Describe various file opening modes with examples.
13) Explain the steps for sequential file read and write operations.
14) Differentiate between binary and ASCII files with suitable examples.
15) Write a short note on random access file operations in C++.
16) Write a program to read and write data to a text file using ifstream and ofstream. Explain
function templates and class templates in C++.
17) Write a program using a function template to find the maximum of two numbers.
18) Explain the concept of exception handling in C++ with syntax and example.
19) Discuss various string operations and functions in C++.

Ten mark Questions


11) Explain in detail the different types of file stream classes, file modes, and file operations in
C++ with suitable examples.
12) Discuss in detail about sequential and random access file operations with proper syntax and
example programs.
13) Explain the concept of templates in C++. Write a program demonstrating function and class
templates.
14) Describe exception handling in C++ with suitable example programs showing try, throw,
and catch.
15) Explain about C++ string class, its attributes, and important functions with examples.

You might also like