Object Oriented Programming in C++ - I B.SC AI & ML Material
Object Oriented Programming in C++ - I B.SC AI & ML Material
(Autonomous)
KARUR-3
SUBJECT CODE:25UAIC01
Prepared by
Dr.G.Sudhadevi M.Sc.,M.Phil.,B.Ed.,Ph.D.,
Assistant Professor
UNIT-1
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++
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++
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++
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).
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).
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:
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
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.
Example:
class Counter {
public:
static int count;
Counter() {
count++;
}
void showCount() {
std::cout << "Count: " << 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:
#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 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;
}
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; }
};
In C++, constructors, destructors, and static members have unique characteristics that are
important to understand when used together.
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
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.
#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 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 ;
}
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;
}
};
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 { };
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;
};
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:
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;
}
};
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:
#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
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;
}
};
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.
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:
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.
#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
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
o Class to basic
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;
Initialization
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.
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= #
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 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)}
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
Example:
int main() {
// Declare and initialize an integer array
int numbers[5] = {10, 20, 30, 40, 50};
// Modify an element
numbers[1] = 25;
std::cout << "Modified element at index 1:
" << numbers[1] << std::endl;
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.
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.
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.
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
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
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
Example:
#include <iostream>
#include <memory>
using namespace std;
int main() {
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.
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.
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.
Polymorphism in C++
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):
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
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.
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.
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.
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;
}
For Example, if we want to open the file for reading, we use the following opening
mode: fstream filein("file.txt", ios::in);
Similarly, if we want to open the file for writing, we use the
following: fstream fileout("file.txt", ios::out);
Other File Streams
fstream is not the only file stream provided by C++.There are two more specialized streams:
if (!myFile) {
cout << "Error while opening file." << endl;
} else {
cout << "Existing file opened successfully for reading & appending." << endl;
}
return 0;}
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:
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++ 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.
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;
}
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;
}
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;}
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().
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
Ans:B
2) The class used for reading from a file is _______.
a) ofstream
b) ifstream
c) fstream
d) filebuf
Ans:B
Ans:B
Ans: A
a) Memory allocation
b) Generic programming
c) File management
d) Error handling
Ans:B
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