C++ Class Notes-2
C++ Class Notes-2
UNIT-1
INTRODUCTION TO C++
01 - INTRODUCTION TO C++
02 – KEY CONCEPTS OF OBJECT ORIENTED PROGRAMMING
03 – OBJECT ORIENTED LANGUAGE
04 – C++ DECLARATION
05 - CONTROL STRUCTURE
06 – FUNCTIONS IN C++
Introduction of C++ :-
C++ is a general-purpose programming language that was developed as an
enhancement of the C language to include object-oriented paradigm. It is an imperative and a
compiled language.
C++ is a high-level, general-purpose programming language designed for system and application
programming. It was developed by Bjarne Stroustrup at Bell Labs in 1983 as an extension of the C
programming language. C++ is an object-oriented, multi-paradigm language that supports
procedural, functional, and generic programming styles.
Key concepts of Oops:-
Object-oriented programming aims to implement real-world entities like inheritance, hiding,
polymorphism, etc. in programmingThe main aim of OOP is to bind together the data and the
functions that operate on them so that no other part of the code can access this data except that
function.
There are some basic concepts that act as the building blocks of OOPs i.e.
• CLASS
• OBJECT
• ENCAPSULATION
• ABSTRACTION
• POLYMORPHISM
• INHERITANCE
• DYNAMIC BINDING
• MESSAGE PASSING
1|Page
Prepared by:1st Shift Students || Guided by : Dr.P.Kokila
B.Sc(CS) , LRG Govt.Arts College for wornen, Tirupur
C++ Class Notes,
1. Class:
A class is a user-defined data type. It consists of data members and member functions, which can
be accessed and used by creating an instance of that class. It represents the set of properties or
methods that are common to all objects of one type. A class is 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,
Mileage range, etc. So here, Car is the class, and wheels, speed limits, mileage are their properties.
2. Object:
It is a basic unit of Object-Oriented Programming and represents the real-life entities. An Object
is an instance of a Class. When a class is defined, no memory is allocated but when it is instantiated
(i.e. an object is created) memory is allocated. An object has an identity, state, and behavior. Each
object contains data and code to manipulate the data
For example “Dog” is a real-life Object, which has some characteristics like color, Breed, Bark,
Sleep, and Eats.
3. Data Abstraction:
Data abstraction is one of the most essential and important features of object-oriented
programming. Data abstraction refers to providing only essential information about the data to
the outside world, hiding the background details or implementation.
4. Encapsulation:
Encapsulation is defined as the wrapping up of data under a single unit. It is the mechanism that
binds together code and the data it manipulates In Encapsulation, the variables or data of a class
2|Page
Prepared by:1st Shift Students || Guided by : Dr.P.Kokila
B.Sc(CS) , LRG Govt.Arts College for wornen, Tirupur
C++ Class Notes,
are hidden from any other class and can be accessed only through any member function of their
class in which they are declared. As in encapsulation, the data in a class is hidden from other
classes, so it is also known as data-hiding.
5. Inheritance:
Inheritance is an important pillar of OOP(Object-Oriented Programming). The capability of a class
to derive properties and characteristics from another class is called Inheritance. When we write a
class, we inherit properties from other classes. So when we create a class, we do not need to write
all the properties and functions again and again, as these can be inherited from another class that
possesses it. Inheritance allows the user to reuse the code whenever possible and reduce its
redundancy.
6.Polymorphism:
The word polymorphism means having many forms. In simple words, we can define polymorphism
as the ability of a message to be displayed in more than one form. For example, A person at the
same time can have different characteristics. Like a man at the same time is a father, a husband,
an employee. So the same person posses different behavior in different situations. This is called
polymorphism.
3|Page
Prepared by:1st Shift Students || Guided by : Dr.P.Kokila
B.Sc(CS) , LRG Govt.Arts College for wornen, Tirupur
C++ Class Notes,
7.Dynamic Binding:
In dynamic binding, the code to be executed in response to the function call is decided at runtime.
Dynamic binding means that the code associated with a given procedure call is not known until
the time of the call at run time. Dynamic Method Binding One of the main advantages of
inheritance is that some derived class D has all the members of its base class B. Once D is not
hiding any of the public members of B, then an object of D can represent B in any context where
a B could be used.
This feature is known as subtype polymorphism.
8.Message Passing:
It is a form of communication used in object-oriented programming as well as parallel
programming. Objects communicate with one another by sending and receiving information to
each other. A message for an object is a request for execution of a procedure and therefore will
invoke a function in the receiving object that generates the desired results. Message passing
involves specifying the name of the object, the name of the function, and the information to be
sent.
Advantages of C++:
• C++ is an object-oriented programming language. It may be a collection of
commands, which tell the pc to try to do “something.” This collection of
commands is typically called C++ ASCII text files.
• C++ could also be a problem-oriented language that’s much easier to use
than the other lowlevel languages like binary coding. It takes much more space
than low-level languages but it’s much easier to understand and learn.
• C++ program has many advantages when it involves programming, All C++
program standalone files must use the foremost function to allow the program
to start out up and motivate its functions.
4|Page
Prepared by:1st Shift Students || Guided by : Dr.P.Kokila
B.Sc(CS) , LRG Govt.Arts College for wornen, Tirupur
C++ Class Notes,
• C++ program can support unions and structures that are a mix of stand-
alone and puttogether files, It uses the standard C++ application mentioned as
“.cpp”, C++ uses the reserved library word mentioned as “goto” that’s the same
as Java’s continue, or break commands.
• The global data and global functions are used within C++ that aren’t utilized
in many other high-level languages within the pc sciences and it is an advantage
to the programming languages.
Disadvantages of C++:
• One major problem in C++ is when the info points to an equivalent thing
from two different starting points, this causes a serious problem, the C++
program will still have involved problems within the coding.
• Java’s uni-code to the ASCII rules is 16-bit, while C++ program is 8-bit only,
So, C++ may be a less impressive programming language but saves the memory.
• C++ program is complex during a very large high-level program, C++ is
employed for platform-specific application commonly, For the actual OS or
platform, the library set is typically chosen.
• C++ program can’t support garbage pickup, It’s not secure because it’s a
pointer, friend function, and global variable and it’s no support for threads built-
in.
• C++ programs are often heavy if it’s not careful, C++ program allows classes
and thus the functions with an equivalent name and overloaded functions thus
the symbol mangling system must be used, It can easily be wrapped in C functions
though.
• Used for printing output to the standard output (usually the console).
• Example: std::cout << "Hello, World!";
4. Error Stream (std::cerr and std::clog):
5|Page
Prepared by:1st Shift Students || Guided by : Dr.P.Kokila
B.Sc(CS) , LRG Govt.Arts College for wornen, Tirupur
C++ Class Notes,
```cpp
#include <iostream> // Required for I/O operations
int main() {
6|Page
Prepared by:1st Shift Students || Guided by : Dr.P.Kokila
B.Sc(CS) , LRG Govt.Arts College for wornen, Tirupur
C++ Class Notes,
### 2. Encapsulation
Encapsulation is the bundling of data and methods that operate on that data. In C++, the stream
classes encapsulate the functionalities needed to perform I/O operations.
```cpp
#include <iostream>
class FileHandler {
private:
std::ifstream file; // encapsulated file stream
public:
void openFile(const std::string& filename) {
file.open(filename);
}
std::string readLine() {
std::string line;
if (std::getline(file, line)) {
return line;
}
return ""; // return an empty string if failed
}
void closeFile() {
file.close();
}
};
```
3. Inheritance
C++ supports inheritance in its I/O streams, allowing you to create your own types of streams by
inheriting from existing classes.
```cpp
#include <iostream>
#include <fstream>
7|Page
Prepared by:1st Shift Students || Guided by : Dr.P.Kokila
B.Sc(CS) , LRG Govt.Arts College for wornen, Tirupur
C++ Class Notes,
int main() {
MyFileStream myFile;
myFile.open("example.txt");
myFile << "Appending this line to the file." << std::endl;
myFile.close();
return 0;
}
```
4. Polymorphism
C++ I/O allows the use of polymorphism through function overloading. For example,
`std::ostream` has overloaded operators that allow different data types to be output with the `<<`
operator.
```cpp
#include <iostream>
int main() {
print(std::cout, 42); // Calls print(int)
print(std::cout, 3.14); // Calls print(double)
print(std::cout, "Hello"); // Calls print(string)
return 0;
8|Page
Prepared by:1st Shift Students || Guided by : Dr.P.Kokila
B.Sc(CS) , LRG Govt.Arts College for wornen, Tirupur
C++ Class Notes,
}
```
### 5. Abstraction
Through abstract classes and interfaces, C++ minimizes the complexity of how I/O operations are
implemented.
```cpp
#include <iostream>
#include <string>
#include <memory>
class OutputDevice {
public:
virtual void write(const std::string& message) = 0; // Pure virtual function
};
public:
FileOutput(const std::string& filename) {
file.open(filename);
}
~FileOutput() {
file.close(); // Clean up
}
};
int main() {
9|Page
Prepared by:1st Shift Students || Guided by : Dr.P.Kokila
B.Sc(CS) , LRG Govt.Arts College for wornen, Tirupur
C++ Class Notes,
return 0;
}
```
Formatted I/O:
C++ helps you to format the I/O operations like determining the number of digits to be displayed
after the decimal point, specifying number base etc.
Example:
• If we want to add + sign as the prefix of out output, we can use the formatting to do so:
• stream.setf(ios::showpos)
If input=100, output will be +100
```cpp
#include <iostream>
#include <fstream>
#include <vector>
Unformatted I/O:
In this article, we will discuss the unformatted Input/Output operations In C++.
Using objects cin and cout for the input and the output of data of various types is possible because
of overloading of operator >> and << to recognize all the basic C++ types. The operator >> is
overloaded in the istream class and operator << is overloaded in the ostream class.
The general format for reading data from the keyboard:
cin >> var1 >> var2 >> …. >> var_n;
10 | P a g e
Prepared by:1st Shift Students || Guided by : Dr.P.Kokila
B.Sc(CS) , LRG Govt.Arts College for wornen, Tirupur
C++ Class Notes,
In C++, unformatted I/O refers to raw data input and output without any formatting applied. This
means that the data is read from or written to streams in a straightforward manner. Unformatted
I/O operations typically operate on raw bytes and do not interpret the data in a way that would
change its representation (e.g., no conversion of numeric types or no padding for alignment).
```cpp
#include <iostream>
#include <fstream>
int main() {
// Create some binary data
const char data[] = { 'A', 'B', 'C', 'D', 'E' };
if (!outFile) {
std::cerr << "Error opening file for writing!" << std::endl;
return 1;
}
C++ Declaration:
In C++, a declaration is a statement that specifies the type and name of a variable, a function, a
class, or any other user-defined type. Declarations tell the compiler about the existence and type
of a variable or function without allocating memory or defining its functionality. Below are several
examples of different kinds of declarations in C++:
Variable Declaration
```cpp
int x; // Declares an integer variable `x`
float y; // Declares a floating-point variable `y`
char c; // Declares a character variable `c`
```
Function Declaration
11 | P a g e
Prepared by:1st Shift Students || Guided by : Dr.P.Kokila
B.Sc(CS) , LRG Govt.Arts College for wornen, Tirupur
C++ Class Notes,
A function declaration (also known as a function prototype) informs the compiler about the
function's name, return type, and parameters without providing the implementation.
```cpp
void myFunction(int a, float b); // Function declaration
```
Class Declaration
A class declaration defines a data type that encapsulates data and functions. The definition can
also include member variables and member functions.
Parts of c++ program:
A C++ program typically consists of the following structural parts: header inclusions (using
#include directives), namespace declarations, class definitions (if applicable), function definitions
(including the main function), variables, comments, and executable statements within the
functions; essentially, a combination of header files, code blocks defining classes and functions,
and the core logic within the "main" function where the program execution starts.
Key components:
Header Files:
Used with #include directives to access pre-defined functions and data types from the C++
standard library.
Examples: <iostream> for input/output operations, <vector> for dynamic arrays.
Namespace Declarations:
Used to organize code by grouping related functions and variables under a specific name,
preventing naming conflicts.
Example: using namespace std; to access standard library elements directly.
Class Definitions:
Blueprints for creating objects with their own data members (variables) and member functions
(methods).
Function Definitions:
Blocks of code that perform a specific task, including the main function which is the entry point of
the program.
Variables:
Named storage locations to hold data values of different data types (int, float, string, etc.)
Comments:
Human-readable explanations within the code, ignored by the compiler, to improve
understanding and maintainability.
12 | P a g e
Prepared by:1st Shift Students || Guided by : Dr.P.Kokila
B.Sc(CS) , LRG Govt.Arts College for wornen, Tirupur
C++ Class Notes,
Tokens:
Tokens in C++ are the fundamental building blocks of a program, recognized by the compiler as
distinct units with meaning. They are categorized into several types:
Keywords: Reserved words with predefined meanings (e.g., int, float, if, else, for, while).
Identifiers: Names given to variables, functions, classes, etc., defined by the programmer (e.g.,
myVariable, calculateArea).
Constants: Fixed values that cannot be changed during program execution (e.g., 10, 3.14, "Hello").
Operators: Symbols that perform specific operations (e.g., +, -, *, /, =, ==).
Special Symbols: Characters with specific meanings in C++ syntax (e.g., ;, {}, (), []).
Strings: Sequence of characters enclosed in double quotes, treated as a single unit (e.g., "This is a
string").
13 | P a g e
Prepared by:1st Shift Students || Guided by : Dr.P.Kokila
B.Sc(CS) , LRG Govt.Arts College for wornen, Tirupur
C++ Class Notes,
Eg.
Basic data types are the fundamental data types provided by C++. They serve as the building
blocks for data manipulation.
- **Integer Types**
```cpp
int x = 10; // A standard integer
long y = 20L; // A long integer
short z = 5; // A short integer
```
14 | P a g e
Prepared by:1st Shift Students || Guided by : Dr.P.Kokila
B.Sc(CS) , LRG Govt.Arts College for wornen, Tirupur
C++ Class Notes,
- **Floating-Point Types**
```cpp
float a = 5.75f; // A single-precision floating-point
double b = 3.142; // A double-precision floating-point
```
- **Character Type**
```cpp
char ch = 'A'; // A character
```
Derived datatype:
Derived data types in C++ are data types constructed from the fundamental, built-in data types.
They provide a way to group and organize data for more complex data structures. The main
derived data types in C++ are:
Eg.
In C++, **derived data types** are types that are derived from fundamental (or basic) data types.
They allow you to create complex data structures and other constructs that enhance your
programming capabilities. Here are the main categories of derived data types in C++:
### 1. Arrays
An array is a collection of elements of the same type, stored in contiguous memory locations. It
can hold multiple values under a single name.
**Example:**
```cpp
int numbers[5] = {1, 2, 3, 4, 5}; // Array of integers
```
### 2. Pointers
A pointer is a variable that holds the memory address of another variable. Pointers can be used
to reference and manipulate variable addresses directly.
**Example:**
```cpp
int a = 10; // An integer variable
int* p = &a; // Pointer to an integer, holding the address of 'a'
std::cout << "Value of a: " << *p << std::endl; // Dereferencing the pointer
15 | P a g e
Prepared by:1st Shift Students || Guided by : Dr.P.Kokila
B.Sc(CS) , LRG Govt.Arts College for wornen, Tirupur
C++ Class Notes,
Arrays: An array is a collection of elements of the same data type stored in contiguous memory
locations. Arrays provide a way to store and access multiple values of the same type using a single
identifier.
Example:
int numbers[5] = {1, 2, 3, 4, 5}; // An array of 5 integers
n C++, an **array** is a collection of elements of the same type, stored in contiguous memory
locations. You can think of an array as a way to group multiple variables of the same type under a
single name, allowing you to easily manage and access them using indices.
**Syntax:**
```cpp
type arrayName[size];
```
Here's a simple example of how to declare, initialize, and use an array in C++:
```cpp
#include <iostream>
int main() {
// Declaration and initialization of an array
int numbers[5] = {10, 20, 30, 40, 50};
Pointers: A pointer is a variable that stores the memory address of another variable. Pointers are
used for dynamic memory allocation, passing data to functions efficiently, and working with data
structures like linked lists.
Example:
int x = 10;
int* ptr = &x; // ptr stores the address of x
16 | P a g e
Prepared by:1st Shift Students || Guided by : Dr.P.Kokila
B.Sc(CS) , LRG Govt.Arts College for wornen, Tirupur
C++ Class Notes,
Pointers are a powerful feature in C++ that allow you to manage memory and manipulate data
more efficiently. A pointer is a variable that stores the memory address of another variable. They
are essential for dynamic memory allocation, array manipulation, and implementing data
structures like linked lists and trees.
1. **Declaration**:
To declare a pointer, use the `*` (asterisk) symbol. The type of the pointer indicates what type
of variable it points to.
**Syntax**:
```cpp
type *pointerName;
```
**Example**:
```cpp
int *p; // Declaration of a pointer to an integer
```
2. **Initialization**:
Pointers can be initialized to point to a variable using the address-of operator `&`.
**Example**:
```cpp
int var = 5;
int *p = &var; // p now holds the address of var
Functions: A function is a block of code that performs a specific task. Functions are used to
modularize code, improve readability, and promote code reuse. Functions in C++ are blocks of
code that perform a specific task. They allow you to encapsulate code logic, promote code
reusability, and improve the structure of your program. Functions can take inputs (called
parameters) and can produce output (return values).
```cpp
returnType functionName(parameters) {
// Function body
17 | P a g e
Prepared by:1st Shift Students || Guided by : Dr.P.Kokila
B.Sc(CS) , LRG Govt.Arts College for wornen, Tirupur
C++ Class Notes,
// Code to be executed
return value; // (optional, based on returnType)
}
```
- **returnType**: The data type of the value returned by the function. If the function doesn’t
return a value, use `void`.
- **functionName**: The name of the function, which should be descriptive of its purpose.
- **parameters**: (Optional) A list of input parameters enclosed in parentheses. This allows
passing values to the function. You can also specify types for each parameter.
Example:
int add(int a, int b) {
return a + b;
}
References: A reference is an alias for an existing variable. It provides another way to access and
modify the original variable.
Example:
int x = 10;
int& ref = x; // ref is a reference to x
ref = 20; // x is now 20
Classes and Structures: These are user-defined data types that can group variables of different
data types and functions (methods) into a single unit. They are the building blocks of object-
oriented programming.
Example:
class Dog {
public:
string name;
int age;
void bark() {
cout << "Woof!" << endl;
}};
Unions: A union is a special data type that allows storing different data types in the same memory
location. Only one member of a union can be used at a time.a union is a special data type that
allows storing different data types in the same memory location. Unlike structures, where each
member has its own memory, a union uses the same memory for all its members. This means that
the space allocated for a union is equal to the size of its largest member.
Unions are useful in scenarios where you need to manage different types of data but do not need
to store them simultaneously. This can lead to efficient memory usage.
18 | P a g e
Prepared by:1st Shift Students || Guided by : Dr.P.Kokila
B.Sc(CS) , LRG Govt.Arts College for wornen, Tirupur
C++ Class Notes,
```cpp
union UnionName {
dataType1 member1;
dataType2 member2;
...
};
```
```cpp
#include <iostream>
union Data {
int intValue;
float floatValue;
char charValue;
};
Example:
union Data {
int i;
float f;
char str[20];
};
Enumerations: An enumeration is a user-defined data type that consists of a set of named integer
constants. Enumerations make code more readable and maintainable by providing meaningful
names for values.
Example:
enum Color {
RED,
GREEN,
BLUE
};
These derived data types extend the capabilities of C++ and allow for more complex and organized
data representation and manipulation. They are essential tools for developing efficient and robust
software.
19 | P a g e
Prepared by:1st Shift Students || Guided by : Dr.P.Kokila
B.Sc(CS) , LRG Govt.Arts College for wornen, Tirupur
C++ Class Notes,
Control Structure:-
In C++, control structures are used to dictate the flow of execution of a program based on certain
conditions. These structures enable you to make decisions, repeat actions, and manage the
program's execution order. Control structures in C++ can be broadly categorized into:
The sequential control structure is the simplest form and involves executing statements in a
linear manner, from top to bottom. There is no branching or loop; the program executes each
statement one after another.
```cpp
#include <iostream>
using namespace std;
int main() {
cout << "Hello, World!" << endl;
cout << "Welcome to C++ programming!" << endl;
return 0;
}
```
20 | P a g e
Prepared by:1st Shift Students || Guided by : Dr.P.Kokila
B.Sc(CS) , LRG Govt.Arts College for wornen, Tirupur
C++ Class Notes,
1. **`if` statement**
2. **`if-else` statement**
3. **`else if` ladder**
4. **`switch` statement**
5. **Conditional (ternary) operator**
The `if` statement is the simplest form of selection. It executes a block of code only if the specified
condition is true.
```cpp
#include <iostream>
using namespace std;
int main() {
int number;
cout << "Enter a number: ";
cin >> number;
if (number > 0) {
cout << "The number is positive." << endl;
}
1. **`while` loop**
2. **`do-while` loop**
3. **`for` loop**
4. **Range-based `for` loop** (C++11 and later)
21 | P a g e
Prepared by:1st Shift Students || Guided by : Dr.P.Kokila
B.Sc(CS) , LRG Govt.Arts College for wornen, Tirupur
C++ Class Notes,
The `while` loop repeatedly executes a block of code as long as the specified condition is true. The
condition is checked before the execution of the loop body.
```cpp
#include <iostream>
using namespace std;
int main() {
int count = 0;
return 0;
}
```
4. **Transfer Control Structure**
Control transfer structures in C++ are constructs that control the flow of execution in a program.
They allow you to jump to different parts of the code based on certain conditions or
unconditionally. The main types of transfer control structures in C++ include:
1. **Conditional Statements**
2. **Jump Statements**
3. **Function Calls**
These are used to execute different branches of code based on certain conditions.
The `if` statement allows you to execute a block of code if a specified condition is true.
```cpp
#include <iostream>
using namespace std;
int main() {
int number = 10;
22 | P a g e
Prepared by:1st Shift Students || Guided by : Dr.P.Kokila
B.Sc(CS) , LRG Govt.Arts College for wornen, Tirupur
C++ Class Notes,
if (number > 0) {
cout << "The number is positive." << endl;
}
return 0;
}
```
#### b. `if-else`
23 | P a g e
Prepared by:1st Shift Students || Guided by : Dr.P.Kokila
B.Sc(CS) , LRG Govt.Arts College for wornen, Tirupur
C++ Class Notes,
if (condition) {
// Statements to execute if
// condition is true
}
Here if the condition is true then the code inside the if block will be executed otherwise not.
Flowchart of if
Example of if
The below example demonstrates the use of the if statement by finding if the age of a person is
greater than 18 or not. if the condition is true then he/she is allowed to vote.
#include<iostream>
using namespace std;
int main()
{
int age = 19;
// Check if age is greater than 18
// vote eligiblity
if (age > 18)
{
cout << "allowed to vote";
}
return 0;
Output
allowed to vote
2. if-else Statement
The if else is a decision-making statement allows us to make a decision based on the evaluation
of a given condition. If the given condition evaluates to true then the code inside the 'if' block is
24 | P a g e
Prepared by:1st Shift Students || Guided by : Dr.P.Kokila
B.Sc(CS) , LRG Govt.Arts College for wornen, Tirupur
C++ Class Notes,
executed and in case the condition is false, the code inside the 'else' block is executed. Syntax of
if-else
if (condition) {
// Executes this block if
// condition is true
}
else {
// Executes this block if
// condition is false
}
Flowchart of if-else
Example of if-else
The below example demonstrates the use of an if-else statement to find if the given number is
positive or nonpositive.
Example:
#include <iostream>
using namespace std;
int main()
{
int n = 5;
// Using if-else to determine if the number is positive
// or non positive
if (n > 0)
{
cout << "number is positive.";
}
else
{
cout << "number is non-positive.";
}
return 0;
25 | P a g e
Prepared by:1st Shift Students || Guided by : Dr.P.Kokila
B.Sc(CS) , LRG Govt.Arts College for wornen, Tirupur
C++ Class Notes,
}
Output
number is positive.
3. if else if Ladder
The if else if Ladder statements allow us to include additional situations after the preliminary if
condition. The 'else if' condition is checked only if the above condition is not true, and the `else`
is the statement that will be executed if none of the above conditions is true. If some condition is
true, then no only the associated block is executed. Syntax if else if Ladder
if (condition1) { // Statements 1
}
else if (condition2) {
// Statements 2
}
else {
// Else body
}
We can use multiple else if statements with an if-else pair to specify different conditions.
Flowchart of if-else-if Ladder
26 | P a g e
Prepared by:1st Shift Students || Guided by : Dr.P.Kokila
B.Sc(CS) , LRG Govt.Arts College for wornen, Tirupur
C++ Class Notes,
}
// if above above if statement is not true then we check
// this else if condition if it evalutes to true print
// growing age
else if (age >= 1 and age <= 18)
{
cout << "Growing stage";
}
// if none of above condition is true print adult
Else
{
cout << "adult";
}
return 0;
}
Output
Growing stage
4. Nested if else
The nested if else statement contains an 'if' statement inside another 'if' statement. This structure
lets in more complex selection-making by way of comparing multiple conditions. In this type of
statement, multiple conditions are checked, and then the body of the last if statement is executed.
Syntax of Nested if else
if(condition1) { // Code to be executed if(condition2) {
// Code to be executed
}
else {
// Code to be executed
}
}
else {
// code to be executed
}
Flowchart of Nested if else
27 | P a g e
Prepared by:1st Shift Students || Guided by : Dr.P.Kokila
B.Sc(CS) , LRG Govt.Arts College for wornen, Tirupur
C++ Class Notes,
28 | P a g e
Prepared by:1st Shift Students || Guided by : Dr.P.Kokila
B.Sc(CS) , LRG Govt.Arts College for wornen, Tirupur
C++ Class Notes,
29 | P a g e
Prepared by:1st Shift Students || Guided by : Dr.P.Kokila
B.Sc(CS) , LRG Govt.Arts College for wornen, Tirupur
C++ Class Notes,
Output
40
6. Jump Statements
Jump statements are used to alter the normal flow of the code. If you want to break the flow of
the program without any conditions, then these jump statements are used. C++ provides four
types of jump statements.
A) break
break is a control flow statement that is used to terminate the loop and switch statements
whenever a break statement is encountered and transfer the control to the statement just after
the loop.
break statement is generally used when the actual number of iterations are not predefined, so we
want to terminate the loop based on some conditions.
Example
#include <iostream> using namespace std;
int main()
{
for (int i = 0; i < 5; i++) {
// if i become 3 then break the loop and move to
// next statement out of loop
if (i == 3)
{
break;
}
cout << i << endl;
}
// next statements return 0;
}
Output
0
1
2
B) continue
The continue statement is used to skip the loop body for the current iteration and continue from
the next iteration. Unlike the break statement which terminates the loop completely, continue
allows us just to skip one iteration and continue with the next iteration.
Example
#include <iostream>
using namespace std;
int main()
{
for (int i = 0; i < 5; i++)
{
// if i become 3 then skip the rest body of loop and
30 | P a g e
Prepared by:1st Shift Students || Guided by : Dr.P.Kokila
B.Sc(CS) , LRG Govt.Arts College for wornen, Tirupur
C++ Class Notes,
31 | P a g e
Prepared by:1st Shift Students || Guided by : Dr.P.Kokila
B.Sc(CS) , LRG Govt.Arts College for wornen, Tirupur
C++ Class Notes,
Example
#include <iostream>
using namespace std;
// Function to add two numbers and returns the result
int add(int a, int b)
{
int sum = a + b; return sum; // Return the sum to the calling code
}
int main()
{
int res = add(3, 5); cout << "The sum is: " << res << endl; return 0;
}
Output
The sum is: 8
Loops in c++
• for Loop
• while Loop
• do while Loop for Loop
In C++, for loop is an entry-controlled loop that is used to execute a block of code repeatedly for
the given number of times. It is generally preferred over while and do-while loops in case the
number of iterations is known beforehand
Example
#include <bits/stdc++.h>
using namespace std;
int main()
{
// for loop to print "Hi" 5 times
for (int i = 5; i < 10; i++)
{
cout << "Hi" << endl; }
return 0;
}
Output
Hi
Hi
Hi
Hi
Hi
32 | P a g e
Prepared by:1st Shift Students || Guided by : Dr.P.Kokila
B.Sc(CS) , LRG Govt.Arts College for wornen, Tirupur
C++ Class Notes,
while Loop
While studying for loop, we have seen that the number of iterations is known beforehand,
i.e.
the number of times the loop body is needed to be executed is known to us. while loop is used in
situations where we do not know the exact number of iterations of the loop beforehand. It is an
entry-controlled loop whose execution is terminated on the basis of the test conditions.
return 0;
}
Output
12345
33 | P a g e
Prepared by:1st Shift Students || Guided by : Dr.P.Kokila
B.Sc(CS) , LRG Govt.Arts College for wornen, Tirupur
C++ Class Notes,
do while Loop
The do-while loop is also a loop whose execution is terminated on the basis of test conditions. The
main difference between a do-while loop and the while loop is in the do-while loop the condition
is tested at the end of the loop body, i.e. do-while loop is exit controlled whereas the other two
loops are entry-controlled loops. So, in a do-while loop, the loop body will execute at least once
irrespective of the test condition. Syntax
do {
// Body of the loop
// Update expression } while (condition);
Example
#include <iostream>
using namespace std;
int main()
{
// Initialization int i = 1;
// while loop that starts with i = 1 and ends
// when i is greater than 5.
do
{
cout << i << " ";
// Updation
i++;
}
while (i <= 5);
return 0;
}
Output
12345
Functions in C++
A function is a set of statements that takes input, does some specific computation, and produces
output. The idea is to put some commonly or repeatedly done tasks together to make a function
so that instead of writing the same code again and again for different inputs, we can call this
function.
Syntax:
34 | P a g e
Prepared by:1st Shift Students || Guided by : Dr.P.Kokila
B.Sc(CS) , LRG Govt.Arts College for wornen, Tirupur
C++ Class Notes,
Syntax of Function
Example
#include <iostream>
using namespace std;
// Following function that takes two parameters 'x' and 'y' // as input and returns max of two input
numbers
int max(int x, int y)
{
if (x > y)
return x;
else
return y;
}
// main function that doesn't receive any parameter and
// returns integer
int main()
{
int a = 10, b = 20;
// Calling above function to find max of 'a' and 'b' int m = max(a, b);
cout << "m is " << m;
return 0;
}
Output
m is 20
35 | P a g e
Prepared by:1st Shift Students || Guided by : Dr.P.Kokila
B.Sc(CS) , LRG Govt.Arts College for wornen, Tirupur
C++ Class Notes,
A copy of the value is passed to the function An address of value is passed to the
function
Changes made inside the function are not Changes made inside the function are
reflected on other functions reflected outside the function as well
Actual and formal arguments will be Actual and formal arguments will be
created at different memory location created at same memory location
An inline function is defined using the `inline` keyword before the function’s definition. The main
purpose is to tell the compiler to attempt to replace the function call with the actual function
code.
1. **Reduced Function Call Overhead**: Since inline functions are expanded in place, there is no
need for the overhead of a regular function call (e.g., stack frame creation, jumping to the function
code, etc.).
3. **Code Clarity and Organization**: Inline functions can help in keeping the code clean and
organized, particularly when working with small utility functions.
Syntax:
36 | P a g e
Prepared by:1st Shift Students || Guided by : Dr.P.Kokila
B.Sc(CS) , LRG Govt.Arts College for wornen, Tirupur
C++ Class Notes,
1. **Same Name, Different Signatures**: Overloaded functions must differ in their signatures,
which are defined by the number and/or types of their parameters.
2. **Return Type Independence**: The return type of an overloaded function does not count
towards its signature, meaning you cannot overload functions solely based on different return
types.
3. **Compile-Time Resolution**: The C++ compiler resolves which function to call based on the
function signature at compile time, making it a compile-time polymorphism.
37 | P a g e
Prepared by:1st Shift Students || Guided by : Dr.P.Kokila
B.Sc(CS) , LRG Govt.Arts College for wornen, Tirupur
C++ Class Notes,
```cpp
#include <iostream>
class Calculator {
public:
add(int a, int b) add(double a, double b)
#include <iostream>
using namespace std;
void add(int a, int b)
{
cout << "sum = " << (a + b);
}
void add(double a, double b)
{
cout << endl << "sum = " << (a + b);
}
// Driver code
int main()
{
add(10, 2);
add(5.3, 6.2);
return 0;
}
Output
sum = 12 sum = 11.5
Parameters should have a different number
add(int a, int b) add(int a, int b, int c)
#include <iostream>
using namespace std;
void add(int a, int b)
{
cout << "sum = " << (a + b);
}
void add(int a, int b, int c)
{
cout << endl << "sum = " << (a + b + c);
}
38 | P a g e
Prepared by:1st Shift Students || Guided by : Dr.P.Kokila
B.Sc(CS) , LRG Govt.Arts College for wornen, Tirupur
C++ Class Notes,
39 | P a g e
Prepared by:1st Shift Students || Guided by : Dr.P.Kokila
B.Sc(CS) , LRG Govt.Arts College for wornen, Tirupur
C++ Class Notes,
UNIT-2
CLASSES AND OBJECT
40 | P a g e
Prepared by:1st Shift Students || Guided by : Dr.P.Kokila
B.Sc(CS) , LRG Govt.Arts College for wornen, Tirupur
C++ Class Notes,
Public: Members declared as public can be accessed from outside the class.
Private: Members declared as private can only be accessed within the class itself.
Protected: Members declared as protected can be accessed within the class and by derived
classes.
If we do not specify the access specifier, the private specifier is applied to every member by
default.
Example of Access Specifiers
// C++ program to demonstrate accessing of data members
41 | P a g e
Prepared by:1st Shift Students || Guided by : Dr.P.Kokila
B.Sc(CS) , LRG Govt.Arts College for wornen, Tirupur
C++ Class Notes,
#include <bits/stdc++.h>
using namespace std;
class Geeks {
private:
string geekname;
// Access specifier
public:
// Member Functions()
void setName(string name) { geekname = name; }
42 | P a g e
Prepared by:1st Shift Students || Guided by : Dr.P.Kokila
B.Sc(CS) , LRG Govt.Arts College for wornen, Tirupur
C++ Class Notes,
class Geeks {
public:
string geekname;
int id;
// printname is not defined inside class definition
void printname();
// printid is defined inside class definition
void printid() { cout << "Geek id is: " << id; }
};
// Definition of printname using scope resolution operator
// ::
void Geeks::printname()
{
cout << "Geekname is: " << geekname;
}
int main()
{
Geeks obj1;
obj1.geekname = "xyz";
obj1.id = 15;
// call printname()
obj1.printname();
cout << endl;
// call printid()
obj1.printid();
return 0;
}
Output
Geekname is: xyz
Geek id is: 15
Note that all the member functions defined inside the class definition are by default inline, but
you can also make any non-class function inline by using the keyword inline with them. Inline
functions are actual functions, which are copied everywhere during compilation, like pre-
processor macro, so the overhead of function calls is reduced.
Note: Declaring a friend function is a way to give private access to a non-member function.
ARRAYS
An array in C/C++ or be it in any programming language is a collection of similar data items
stored at contiguous memory locations and elements can be accessed randomly using indices of
an array. They can be used to store the collection of primitive data types such as int, float, double,
char, etc of any articular type. To add to it, an array in C/C++ can store derived data types such as
structures, pointers, etc. Given below is the picture representation of an array.
Example:
Let’s consider an example of taking random integers from the user.
43 | P a g e
Prepared by:1st Shift Students || Guided by : Dr.P.Kokila
B.Sc(CS) , LRG Govt.Arts College for wornen, Tirupur
C++ Class Notes,
Array allocation
Array of Objects
When a class is defined, only the specification for the object is defined; no memory or storage is
allocated. To use the data and access functions defined in the class, you need to create objects.
Syntax:
ClassName ObjectName[number of objects];
The Array of Objects stores objects. An array of a class type is also known as an array of objects.In
C++, an array of objects allows you to create an array that consists of instances of a class. This can
be particularly useful when you need to manage a collection of objects of the same type.
Below is a simple example demonstrating how to create and use an array of objects in C++.
```cpp
#include <iostream>
#include <string>
class Car {
public:
std::string brand;
std::string model;
int year;
// Constructor
Car(std::string br, std::string mo, int yr) : brand(br), model(mo), year(yr) {}
44 | P a g e
Prepared by:1st Shift Students || Guided by : Dr.P.Kokila
B.Sc(CS) , LRG Govt.Arts College for wornen, Tirupur
C++ Class Notes,
}
};
Example#1:
Storing more than one Employee data. Let’s assume there is an array of objects for storing
employee data emp[50].
45 | P a g e
Prepared by:1st Shift Students || Guided by : Dr.P.Kokila
B.Sc(CS) , LRG Govt.Arts College for wornen, Tirupur
C++ Class Notes,
cout<<id<<" ";
cout<<name<<" ";
cout<<endl;
}
int main(){
Employee emp; //One member
emp.getdata();//Accessing the function
emp.putdata();//Accessing the function
return 0;
}
Let’s understand the above example –
In the above example, a class named Employee with id and name is being considered.
The two functions are declared-
getdata(): Taking user input for id and name.
putdata(): Showing the data on the console screen.
This program can take the data of only one Employee. What if there is a requirement to add data
of more than one Employee. Here comes the answer Array of Objects. An array of objects can be
used if there is a need to store data of more than one employee. Below is the C++ program to
implement the above approach-
// C++ program to implement
// the above approach
#include<iostream>
using namespace std;
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
46 | P a g e
Prepared by:1st Shift Students || Guided by : Dr.P.Kokila
B.Sc(CS) , LRG Govt.Arts College for wornen, Tirupur
C++ Class Notes,
// the class
void Employee::putdata()
{
cout << id << " ";
cout << name << " ";
cout << endl;
}
// Driver code
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();
}
OUTPUT:
Explanation:
In this example, more than one Employee’s details with an Employee id and name can be stored.
Employee emp[30] – This is an array of objects having a maximum limit of 30 Employees.
Two for loops are being used-
47 | P a g e
Prepared by:1st Shift Students || Guided by : Dr.P.Kokila
B.Sc(CS) , LRG Govt.Arts College for wornen, Tirupur
C++ Class Notes,
First one to take the input from user by calling emp[i].getdata() function.
Second one to print the data of Employee by calling the function emp[i].putdata() function.
Friend Function
In C++, a friend function is a function that is not a member of a class but has access to its private
and protected members. Friend functions are useful when you need to allow specific non-member
functions access to the private data of a class, which is typically not possible with normal
functions.Like a friend class, a friend function can be granted special access to private and
protected members of a class in C++. They are not the member functions of the class but can
access and manipulate the private and protected members of that class for they are declared as
friends.
A friend function can be:
• A global function
• A member function of another class
1. **Access**: Friend functions can access all members (private and protected) of the class that
declares them as friends.
2. **Declaration**: A friend function is declared using the keyword `friend` inside the class
definition.
3. **Scope**: The friend function is not a member of the class. It does not have a `this` pointer.
4. **Multiple Classes**: A friend function can be made a friend of multiple classes.
5. **Not Inherited**: Friendship is not inherited. If class A declares a function as a friend, it does
not mean that derived classes will inherit that friendship.
```cpp
#include <iostream>
#include <string>
48 | P a g e
Prepared by:1st Shift Students || Guided by : Dr.P.Kokila
B.Sc(CS) , LRG Govt.Arts College for wornen, Tirupur
C++ Class Notes,
Syntax:
friend return_type function_name (arguments); // for a global function
or
friend return_type class_name::function_name (arguments); // for a member function of
another class
FRIEND CLASS:
A friend class can access private and protected members of other classes in which it is declared as
a friend. It is sometimes useful to allow a particular class to access private and protected members
of other classes. For example, a LinkedList class may be allowed to access private members of
Node.
We can declare a friend class in C++ by using the friend keyword.
Syntax:
friend class class_name; // declared in the base class
49 | P a g e
Prepared by:1st Shift Students || Guided by : Dr.P.Kokila
B.Sc(CS) , LRG Govt.Arts College for wornen, Tirupur
C++ Class Notes,
Example:
// C++ Program to demonstrate the
// functioning of a friend class
#include <iostream>
using namespace std;
class GFG {
private:
int private_variable;
protected:
int protected_variable;
public:
GFG()
{
private_variable = 10;
protected_variable = 99;
}
50 | P a g e
Prepared by:1st Shift Students || Guided by : Dr.P.Kokila
B.Sc(CS) , LRG Govt.Arts College for wornen, Tirupur
C++ Class Notes,
Member Function:
It is basically a function that can be declared as members of a class. It is usually declared inside
the class definition and works on data members of the same class. It can have access to private,
public, and protected data members of the same class. This function is declared as shown below:
#include<iostream>
using namespace std;
class Item
{
int itemId,quantity;
double price;
public:
void setValue()
{
cout<<"Enter the Item Id:";
cin>>itemId;
cout<<"Enter the Item Price:";
cin>>price;
cout<<"Enter the Quantity:";
cin>>quantity;
}
void display()
{
cout<<endl<<itemId<<"\t"<<price<<"\t"<<quantity;
}
};
51 | P a g e
Prepared by:1st Shift Students || Guided by : Dr.P.Kokila
B.Sc(CS) , LRG Govt.Arts College for wornen, Tirupur
C++ Class Notes,
main()
{
Item _item;
_item.setValue();
_item.display();
return 0;
}
Output
Enter the Item Id: 123
123
Enter the Item Price:25
Enter the Quantity:3
123 25 3
Non-member Function:
The function which is declared outside the class is known as the non-member function of that
class. Below is the difference between the two:
The member function can appear outside of the class body (for instance, in the implementation
file). But, this approach is followed, the member function must be qualified by the name of its
class. This is to identify that function is a member of a particular class. But a non-member function
always appears outside of a class.
Another difference between member functions and non-member functions is how they are called
(or invoked) in the main routine.
52 | P a g e
Prepared by:1st Shift Students || Guided by : Dr.P.Kokila
B.Sc(CS) , LRG Govt.Arts College for wornen, Tirupur
C++ Class Notes,
// Member function
void memberfn(int x)
{
a = x;
cout << "Member function inside"
<< " class declared\n";
}
53 | P a g e
Prepared by:1st Shift Students || Guided by : Dr.P.Kokila
B.Sc(CS) , LRG Govt.Arts College for wornen, Tirupur
C++ Class Notes,
1. Name and Parameter List**: Functions must have the same name but differ in their parameter
type, number of parameters, or both.
2. Return Type**: The return type of the functions cannot be used for distinguishing overloaded
functions. The functions must be distinguishable by their signatures (the combination of the
function name and parameter types).
3. Const Member Functions**: You can overload member functions based on the `const` qualifier;
two functions can have the same name but one can be a `const` member function and the other
not.
4. Inheritance**: Overloaded member functions can be inherited by derived classes.
```cpp
#include <iostream>
Example:
#include <iostream>
class Calculator {
public:
int calculate(int num1, int num2) {
return num1 + num2;
}
double calculate(double num1, double num2) {
return num1 * num2;
}
int calculate(int num1, int num2, int num3) {
return num1 + num2 + num3;
}
};
int main() {
Calculator calc;
std::cout << "Result 1: " << calc.calculate(10, 20) << std::endl;
54 | P a g e
Prepared by:1st Shift Students || Guided by : Dr.P.Kokila
B.Sc(CS) , LRG Govt.Arts College for wornen, Tirupur
C++ Class Notes,
55 | P a g e
Prepared by:1st Shift Students || Guided by : Dr.P.Kokila
B.Sc(CS) , LRG Govt.Arts College for wornen, Tirupur
C++ Class Notes,
56 | P a g e
Prepared by:1st Shift Students || Guided by : Dr.P.Kokila
B.Sc(CS) , LRG Govt.Arts College for wornen, Tirupur
C++ Class Notes,
Default Constructors:
The constructor that takes no argument is called default constructor.
Parameterized Constructors: This type of constructor takes the arguments to initialize the data
members.In C++, a **default constructor** is a constructor that can be called with no arguments.
It can either do nothing or initialize member variables to default values. Default constructors are
an essential part of class design because they allow objects of a class to be created without
needing any specific initialization parameters.
1. **Implicit and Explicit**: If no constructors are defined in a class, the compiler provides an
implicit default constructor. If you define any constructor with parameters, the implicit default
constructor is not provided unless explicitly defined.
2. **Initialization**: Constructors can initialize class member variables. If no specific values are
assigned, the default constructor can set them to default values (e.g., zero for numeric types, an
empty string for strings, etc.).
3. **Syntax**: A default constructor has the same name as the class and does not take any
parameters (or takes parameters with default values).
4. **User-Defined Default Constructor**: You can explicitly define a default constructor to set
member variables or to implement any additional initialization logic.
5. **Destructors**: If a class has a default is a special member function that is invoked when an
object goes out of scope or is explicitly deleted. The primary purpose of a destructor is to free
resources that the object may have acquired during its lifetime, such as dynamic memory, file
handles, or network connections.
Copy Constructors:
Copy constructor creates the object from an already existing object by copying it. a special type
of constructor that initializes a new object as a copy of an existing object. It is crucial for classes
that manage resources, such as dynamic memory, file handles, or other resources that cannot be
simply copied with a default member-wise copy.
1. **Definition**: A copy constructor takes a reference to an object of the same class as its
parameter. The typical syntax is:
```cpp
ClassName(const ClassName &other);
```
57 | P a g e
Prepared by:1st Shift Students || Guided by : Dr.P.Kokila
B.Sc(CS) , LRG Govt.Arts College for wornen, Tirupur
C++ Class Notes,
2. **Implicit Definition**: If you do not define a copy constructor for a class, the C++ compiler
automatically generates a default copy constructor. This automatically generated copy
constructor performs a member-wise copy, which may not be suitable for classes managing
dynamic resources.
3. **Pass by Reference**: The parameter is usually passed by reference to avoid infinite recursion
(a copy constructor would call itself).
4. **Const Reference**: The parameter is typically a `const` reference, meaning the original
object will not be modified by the copy constructor.
Move Constructor:
The move constructor also creates the object from an already existing object but by moving it.a
special type of constructor used to "move" resources from one object to another, rather than
copying them. This is particularly beneficial for performance reasons, especially in situations
involving temporary objects or objects that have acquired resources such as dynamic memory,
file handles, or network connections.
1. **Definition**: A move constructor takes an rvalue reference to an object of the same class.
The syntax is typically:
```cpp
ClassName(ClassName &&other);
```
2. **Rvalue References**: The `&&` syntax indicates that the parameter is an rvalue reference,
allowing the function to bind to temporary objects that would otherwise be moved out of.
3. **Transfer of Ownership**: Unlike a copy constructor, which creates a new object by copying
the values of the members, a move constructor transfers ownership of the resources from the
source object to the new object. After the move, the source object is typically left in a valid but
unspecified state.
4. **Efficiency**: Move constructors can significantly enhance the performance of C++ programs
by eliminating unnecessary deep
Example of Constructor
// C++ program to demonstrate constructors
#include <bits/stdc++.h>
using namespace std;
class Geeks
{
58 | P a g e
Prepared by:1st Shift Students || Guided by : Dr.P.Kokila
B.Sc(CS) , LRG Govt.Arts College for wornen, Tirupur
C++ Class Notes,
public:
int id;
//Default Constructor
Geeks()
{
cout << "Default Constructor called" << endl;
id=-1;
}
//Parameterized Constructor
Geeks(int x)
{
cout <<"Parameterized Constructor called "<< endl;
id=x;
}
};
int main() {
// obj1 will call Default Constructor
Geeks obj1;
cout <<"Geek id is: "<<obj1.id << endl;
Output
Default Constructor called
Geek id is: -1
Parameterized Constructor called
Geek id is: 21
Note: If the programmer does not define the constructor, the compiler automatically creates the
default, copy and move constructor.
Destructors
Destructor (https://www.geeksforgeeks.org/destructors-c/) is another special member function
that is called by the compiler when the scope of the object ends. It deallocates all the memory
previously used by the object of the class so that there will be no memory leaks. The destructor
also have the same name as the class but with tilde(~) as prefix.
Example of Destructor
// C++ program to explain destructors
#include <bits/stdc++.h>
using namespace std;
class Geeks
59 | P a g e
Prepared by:1st Shift Students || Guided by : Dr.P.Kokila
B.Sc(CS) , LRG Govt.Arts College for wornen, Tirupur
C++ Class Notes,
{
public:
int id;
//Definition for Destructor
~Geeks()
{
cout << "Destructor called for id: " << id <<endl;
}
};
int main()
{
Geeks obj1;
obj1.id=7;
int i = 0;
while ( i < 5 )
{
Geeks obj2;
obj2.id=i;
i++;
} // Scope for obj2 ends here
return 0;
} // Scope for obj1 ends here
Output
Destructor called for id: 0
Destructor called for id: 1
Destructor called for id: 2
Destructor called for id: 3
Destructor called for id: 4
Destructor called for id: 7
60 | P a g e
Prepared by:1st Shift Students || Guided by : Dr.P.Kokila
B.Sc(CS) , LRG Govt.Arts College for wornen, Tirupur
C++ Class Notes,
61 | P a g e
Prepared by:1st Shift Students || Guided by : Dr.P.Kokila
B.Sc(CS) , LRG Govt.Arts College for wornen, Tirupur
C++ Class Notes,
UNIT- 3
OPERATOR OVERLOADING
1.Operator overloading
2.Overloading unary operator
3.Overloading binary operator
4.Overloading binary operator using friend function
5.Type conservation
6.Inheritance in c++
7.Virtual base class in C++
8.Abstract class in c++
Key Concepts
1. **Defining an Operator**: You can overload an operator by defining a function with the
keyword `operator` followed by the operator symbol you want to overload.
**Syntax**:
- For member function:
```cpp ReturnType operatorOp(const Type& other);
For non-member function:
```cpp ReturnType operatorOp(const Type& lhs, const Type& rhs);
Example:
62 | P a g e
Prepared by:1st Shift Students || Guided by : Dr.P.Kokila
B.Sc(CS) , LRG Govt.Arts College for wornen, Tirupur
C++ Class Notes,
63 | P a g e
Prepared by:1st Shift Students || Guided by : Dr.P.Kokila
B.Sc(CS) , LRG Govt.Arts College for wornen, Tirupur
C++ Class Notes,
Complex c3 = c1 + c2;
c3.print();
}
Output
12 + i9
Types of Operator Overloading in C++
Operator Overloading can be done by using two approaches, i.e.
• Overloading Unary Operator.
• Overloading Binary Operator.
Unary operators can be overloaded as member functions or as non-member functions. The syntax
involves placing the `operator` keyword followed by the operator symbol you wish to overload.
```cpp
ReturnType operatorOp();
```
```cpp
ReturnType operatorOp(const ClassName& obj);
```
Let's explore a complete example of a simple `Vector` class where we overload the unary `-`
(negation) and the increment `++` operators.
```cpp
64 | P a g e
Prepared by:1st Shift Students || Guided by : Dr.P.Kokila
B.Sc(CS) , LRG Govt.Arts College for wornen, Tirupur
C++ Class Notes,
#include <iostream>
class Vector {
private:
double x, y;
public:
// Constructor
Vector(double x_ = 0, double y_ = 0) : x(x_), y(y_) {}
int main() {
Vector v1(1.0, 2.0);
65 | P a g e
Prepared by:1st Shift Students || Guided by : Dr.P.Kokila
B.Sc(CS) , LRG Govt.Arts College for wornen, Tirupur
C++ Class Notes,
return 0;
}
```
1. **Class Definition**: The `Vector` class contains private members `x` and `y`, which represent
the vector's coordinates.
5. **Friend Function for Output**: A friend function is defined to overload the `<<` operator for
easy printing of `Vector` objects.
6. **Main Function**: The `main` function demonstrates the usage of overloaded unary
operators:
- Negation of a `Vector` object.
66 | P a g e
Prepared by:1st Shift Students || Guided by : Dr.P.Kokila
B.Sc(CS) , LRG Govt.Arts College for wornen, Tirupur
C++ Class Notes,
1. **Intuitive Behavior**: Ensure that the overloaded operator behaves in a way that is intuitive
to users of the class.
2. **Return Values**: Prefix operators generally return a reference to the current object, while
postfix operators return a copy of the object as it was before the increment.
3. **Avoid Side Effects**: Overhead of altering the state in ways that can lead to unexpected
results should be avoided within overloaded operators.
By utilizing operator overloading judiciously, you can create classes that feel natural to use,
enhancing the readability and maintainability of your code. Let us consider overloading (-) unary
operator. In the unary operator function, no arguments should be passed. It works only with one
class object. It is the overloading of an operator operating on a single operand.
Example: Assume that class Distance takes two member objects i.e. feet and inches, and creates
a function by which the Distance object should decrement the value of feet and inches by 1 (having
a single operand of Distance Type).
// C++ program to show unary
// operator overloading
#include <iostream>
using namespace std;
class Distance
{
public:
int feet, inch;
// Constructor to initialize
// the object's value
Distance(int f, int i)
{
this->feet = f;
this->inch = i;
}
// Overloading(-) operator to
67 | P a g e
Prepared by:1st Shift Students || Guided by : Dr.P.Kokila
B.Sc(CS) , LRG Govt.Arts College for wornen, Tirupur
C++ Class Notes,
68 | P a g e
Prepared by:1st Shift Students || Guided by : Dr.P.Kokila
B.Sc(CS) , LRG Govt.Arts College for wornen, Tirupur
C++ Class Notes,
this->inch = i;
}
Output
Total Feet & Inches: 18'11
Explanation: Distance operator+(Distance &d2): Here return type of function is distance and it
uses call by references to pass an argument, d3 = d1 + d2: Here, d1 calls the operator function of
its class object and takes d2 as a parameter, by which the operator function returns the object
and the result will reflect in the d3 object.
Overloading Binary Operator using Friend function
In C++, a binary operator can be overloaded using a friend function. A friend function is
an independent function that is not a member of the class. To overload a binary operator using a
friend function, you need to pass both operands as arguments.
Steps
• Declare the operator overloading function before the friend function
• Declare the function in the scope of the class
• Pass both operands as arguments to the friend function
69 | P a g e
Prepared by:1st Shift Students || Guided by : Dr.P.Kokila
B.Sc(CS) , LRG Govt.Arts College for wornen, Tirupur
C++ Class Notes,
Example
Here's an example of overloading the binary operator + using a friend function:
class demo
{
int x,y;
public:
demo() { x=0; y=0; }
demo(int a, int b) { x=a; y=b; }
friend demo operator + (demo &d1, demo &d2)
{
demo d3;
d3.x = d1.x + d2.x;
d3.y = d1.y + d2.y;
return d3;
}
}
Pictorial View of working of Binary Operator
Type conversion
the process of converting a value of one data type into another. There are two main types
of type conversion, the Type conversion, also known as typecasting or type coercion, is the process
of changing data from one data type to another. Also known as type casting, this is when a user
manually converts a value to a different type using a cast operator.
70 | P a g e
Prepared by:1st Shift Students || Guided by : Dr.P.Kokila
B.Sc(CS) , LRG Govt.Arts College for wornen, Tirupur
C++ Class Notes,
Also known as **automatic type conversion** or **type coercion**, this occurs when the
compiler automatically converts one data type to another without explicit instructions from the
user. This typically happens when you perform operations on mixed data types.
```cpp
#include <iostream>
int main() {
int num = 10;
double decimal = 5.5;
std::cout << "Result: " << result << std::endl; // Output: 15.5
return 0;
}
Examples
Converting an integer to a floating point value
Converting an integer to a string
Converting a string to a number
Converting a date to a time
Where it's used
In programming languages like C, C++, Java, and JavaScript
In database engines like SQL Server
Three types of type conversion are implicit, explicit, and mixed-type expressions:
Implicit type conversion
Also known as coercion, this is when a compiler automatically converts a value to a compatible
type. This happens without any user input.
71 | P a g e
Prepared by:1st Shift Students || Guided by : Dr.P.Kokila
B.Sc(CS) , LRG Govt.Arts College for wornen, Tirupur
C++ Class Notes,
This is the traditional method of casting in C and C++. It uses parentheses to indicate the desired
type.
```cpp
#include <iostream>
int main() {
double num = 9.5;
int intNum = (int)num; // C-style cast
std::cout << "C-style cast: " << intNum << std::endl; // Output: 9
return 0;
}
```
### 2. `static_cast`
72 | P a g e
Prepared by:1st Shift Students || Guided by : Dr.P.Kokila
B.Sc(CS) , LRG Govt.Arts College for wornen, Tirupur
C++ Class Notes,
Mixed-type expressions
This is when a program converts data from one or more subtypes to a supertype at runtime.
Explanation
Type conversion is a process in computer science that changes a value from one data type to
another. It allows for mixed arithmetic operations.
For example, you can convert an integer to a floating-point value or vice versa.
Examples
Implicit type conversion
In C, the compiler automatically converts a value to a compatible type when a value is copied.
Explicit type conversion
In C, you can use a cast operator to manually convert an integer to a double.
73 | P a g e
Prepared by:1st Shift Students || Guided by : Dr.P.Kokila
B.Sc(CS) , LRG Govt.Arts College for wornen, Tirupur
C++ Class Notes,
You can create constructors in your class that take basic data types as parameters. This allows you
to create objects directly from these types.
```cpp
#include <iostream>
class MyClass {
public:
int value;
int main() {
int num = 42;
MyClass obj(num); // Implicit conversion from int to MyClass
Implicit Conversion
• Constructor: Define a constructor that takes the basic data type as an argument.
Example:
class Distance
{
private:
int meters;
public:
// Constructor for implicit conversion from int
Distance(int m) : meters(m) {}
void display()
{
cout << meters << " meters" << endl;
}
};
74 | P a g e
Prepared by:1st Shift Students || Guided by : Dr.P.Kokila
B.Sc(CS) , LRG Govt.Arts College for wornen, Tirupur
C++ Class Notes,
int main()
{
Distance d1 = 10; // Implicit conversion from int to Distance
d1.display();
return 0;
}
In this example:
The Distance(int m) constructor allows implicit conversion from int to Distance.
In main(), Distance d1 = 10; implicitly calls the Distance(int) constructor to create a Distance object
with 10 meters.
To define a conversion constructor, you make it take a single argument (of the desired type) and
declare it as `explicit`. This way, you can control how and when conversion happens, enforcing
that the conversion must be explicit.
• Constructor: Define a constructor that takes the basic data type as an argument.
• Use explicit keyword: This prevents implicit conversions.
```cpp
#include <iostream>
class MyClass {
public:
int value;
int main() {
int num = 50;
75 | P a g e
Prepared by:1st Shift Students || Guided by : Dr.P.Kokila
B.Sc(CS) , LRG Govt.Arts College for wornen, Tirupur
C++ Class Notes,
Example:
class Distance
{
private:
int meters;
public:
// Constructor for explicit conversion from int
explicit Distance(int m) : meters(m) {}
void display()
{
cout << meters << " meters" << endl;
}
};
int main()
{
// Distance d1 = 10; // This will now give a compiler error
Distance d1 = Distance(10); // Explicit conversion
d1.display();
return 0;
}
In this example:
The explicit Distance(int m) constructor prevents implicit conversions from int to Distance.
In main(), Distance d1 = 10; will now result in a compiler error.
Distance d1 = Distance(10); explicitly calls the constructor to create the Distance object.
Explicit Conversion (Using a Conversion Operator)
• Define a conversion operator: A member function within the class that explicitly converts the
class object to a basic data type.
Example:
class Distance
{
private:
int meters;
public:
Distance(int m) : meters(m) {}
// Conversion operator to convert Distance to int
operator int()
const
{
return meters;
76 | P a g e
Prepared by:1st Shift Students || Guided by : Dr.P.Kokila
B.Sc(CS) , LRG Govt.Arts College for wornen, Tirupur
C++ Class Notes,
}
void display()
{
cout << meters << " meters" << endl;
} };
int main()
{
Distance d1(10);
int m = d1; // Implicit conversion using the conversion operator
cout << "Distance in meters: " << m << endl;
return 0;
}
In this example:
The operator int() converts a Distance object to an int representing the number of meters. In
main(), int m = d1; implicitly uses the conversion operator to assign the number of meters to the
int variable m.
Inheritance in C++
The capability of a class to derive properties and characteristics from another class is
called Inheritance. Inheritance is one of the most important feature of Object Oriented
Programming.
Sub Class: The class that inherits properties from another class is called Sub class or Derived Class.
Super Class:The class whose properties are inherited by sub class is called Base Class or Super
class.
The article is divided into following subtopics:
1. Modes of Inheritance
2. Types of Inheritance
Modes of Inheritance
• Public mode: If we derive a sub class from a public base class. Then the public
member of the base class will become public in the derived class and protected members
of the base class will become protected in derived class.
• Protected mode: If we derive a sub class from a Protected base class. Then both
public member and protected members of the base class will become protected in derived
class.
• Private mode: If we derive a sub class from a Private base class. Then both public
member and protected members of the base class will become Private in derived class.
77 | P a g e
Prepared by:1st Shift Students || Guided by : Dr.P.Kokila
B.Sc(CS) , LRG Govt.Arts College for wornen, Tirupur
C++ Class Notes,
Syntax:
class subclass_name : access_mode base_class
{
//body of subclass
};
// C++ program to explain
// Single inheritance
#include <iostream>
using namespace std;
// base class class Vehicle
{
public:
Vehicle()
{
cout << "This is a Vehicle" << endl;
} };
// sub class derived from two base classes class Car: public Vehicle{
};
78 | P a g e
Prepared by:1st Shift Students || Guided by : Dr.P.Kokila
B.Sc(CS) , LRG Govt.Arts College for wornen, Tirupur
C++ Class Notes,
Multiple Inheritance:
Multiple Inheritance is a feature of C++ where a class can inherit from more than one classes. i.e
one sub class is inherited from more than one base class
Syntax:
class subclass_name : access_mode base_class1, access_mode base_class2, ....
{
//body of subclass
};
79 | P a g e
Prepared by:1st Shift Students || Guided by : Dr.P.Kokila
B.Sc(CS) , LRG Govt.Arts College for wornen, Tirupur
C++ Class Notes,
80 | P a g e
Prepared by:1st Shift Students || Guided by : Dr.P.Kokila
B.Sc(CS) , LRG Govt.Arts College for wornen, Tirupur
C++ Class Notes,
{
//creating object of sub class will
//invoke the constructor of base classes Car obj;
return 0;
}
Output:
This is a Vehicle
Objects with 4 wheels are vehicles
Car has 4 Wheels
Hierarchical Inheritance: In this type of inheritance, more than one sub class is inherited from a
single base class. i.e. more than one derived class is created from a single base class.
81 | P a g e
Prepared by:1st Shift Students || Guided by : Dr.P.Kokila
B.Sc(CS) , LRG Govt.Arts College for wornen, Tirupur
C++ Class Notes,
Bus obj2;
return 0;
}
Output:
This is a Vehicle
This is a Vehicle
Hybrid (Virtual) Inheritance: In C++, **hybrid inheritance** refers to a situation where a class
inherits from multiple base classes, which may include a combination of different types of
inheritance: single, multiple, and hierarchical inheritance. A common scenario in hybrid
inheritance occurs when virtual inheritance is also used to address the **diamond problem**.
The diamond problem arises in C++ when two base classes inherit from the same base class, and
a derived class inherits from both of those two base classes. This can cause ambiguity when trying
to access members of the grandparent class, as the compiler may not know which base class's
member to reference.
Virtual Inheritance
**Virtual inheritance** is a mechanism that ensures only one copy of a base class's members is
inherited by a derived class, even if multiple inheritance paths exist. Virtual inheritance solves the
diamond problem by ensuring that there is only one instance of the base class, regardless of how
many times it is referenced.
Here's how hybrid inheritance with virtual inheritance works:Hybrid Inheritance is implemented
by combining more than one type of inheritance. For example: Combining Hierarchical inheritance
and Multiple Inheritance.
Below image shows the combination of hierarchical and multiple inheritance:
82 | P a g e
Prepared by:1st Shift Students || Guided by : Dr.P.Kokila
B.Sc(CS) , LRG Govt.Arts College for wornen, Tirupur
C++ Class Notes,
#include <iostream>
using namespace std;
// base class class Vehicle
{
public: Vehicle()
{
cout << "This is a Vehicle" << endl;
} };
//base class class Fare
{
public: Fare()
{
cout<<"Fare of Vehicle\n";
} };
// first sub class class Car: public Vehicle
{ };
// second sub class class Bus: public Vehicle, public Fare
{ };
// main function int main()
{
// creating object of sub class will
// invoke the constructor of base class
Bus obj2;
return 0;
}
Output:
This is a Vehicle
Fare of Vehicle
Virtual base class in C++
Virtual base classes are used in virtual inheritance in a way of preventing multiple
“instances” of a given class appearing in an inheritance hierarchy when using multiple
inheritances.
83 | P a g e
Prepared by:1st Shift Students || Guided by : Dr.P.Kokila
B.Sc(CS) , LRG Govt.Arts College for wornen, Tirupur
C++ Class Notes,
Virtual inheritance allows a derived class to share a common base class with other derived classes,
ensuring that only one instance of the base class exists in the derived hierarchy. This is achieved
by declaring the base class using the `virtual` keyword during inheritance.
```
A
/\
84 | P a g e
Prepared by:1st Shift Students || Guided by : Dr.P.Kokila
B.Sc(CS) , LRG Govt.Arts College for wornen, Tirupur
C++ Class Notes,
B C
\/
D
```
In this hierarchy:
- Classes B and C both inherit from class A.
- Class D inherits from both B and C.
When class D tries to access members of class A, it encounters the diamond problem because it
has two paths to A (through B and C). Without virtual inheritance, D would have two instances of
A (one through B and one through C),
As we can see from the SSSS figure that data members/function of class A are inherited twice to
class D. One through class B and second through class C. When any data / function member of
class A is accessed by an object of class D, ambiguity arises as to which data/function
Example: To show the need of Virtual Base Class in C++
#include <iostream>
using namespace std;
class A
{
public:
void show()
{
cout << "Hello form A \n";
85 | P a g e
Prepared by:1st Shift Students || Guided by : Dr.P.Kokila
B.Sc(CS) , LRG Govt.Arts College for wornen, Tirupur
C++ Class Notes,
}
};
class B : public A {
};
class C : public A {
};
class D : public B, public C {
};
int main()
{
D object;
object.show();
}
Syntax for Virtual Base Classes:
Syntax 1:
class B : virtual public A
{
};
Syntax 2:
class C : public virtual A
{
};
Example 1
#include <iostream>
using namespace std;
class A
{
public:
int a;
A() //
constructor
{
a = 10;
}
};
class B : public virtual A {
};
class C : public virtual A {
};
class D : public B, public C {
};
int main()
{
86 | P a g e
Prepared by:1st Shift Students || Guided by : Dr.P.Kokila
B.Sc(CS) , LRG Govt.Arts College for wornen, Tirupur
C++ Class Notes,
87 | P a g e
Prepared by:1st Shift Students || Guided by : Dr.P.Kokila
B.Sc(CS) , LRG Govt.Arts College for wornen, Tirupur
C++ Class Notes,
Purpose
• Abstract classes provide a blueprint for derived classes to follow
• They can be used to enforce a certain structure or behavior in derived classes
• They can represent general concepts, such as "Shape" or "Animal" How to create an
abstract class
• Declare at least one pure virtual function in the class declaration
• Use the pure specifier (\(=0\)) in the declaration
How to use an abstract class
• Use pointers and references to abstract class types
• Use the abstract class as a base class for other classes
• Derived classes must implement the pure virtual functions defined in the abstract class
What can't be done with an abstract class
• You can't create an object of an abstract class type
• You can't use an abstract class as a parameter type, a function return type, or the
type of an explicit conversion
Characteristics of abstract classes
Abstract methods: Abstract methods can only have names and arguments, and no other code.
Cannot be instantiated: Abstract classes cannot be instantiated directly. Instead, the constructor
of the abstract class is called when a subclass is instantiated.
Can implement interfaces: Abstract classes can implement interfaces, which define a set of
methods that must be implemented by any class that implements the interface.
Can include constructors and static methods: Abstract classes can have constructors and static
methods.
Can have pointers and references: Abstract classes can have pointers and references.
Play a crucial role in object-oriented programming: Abstract classes provide a blueprint for other
classes to inherit and extend.
88 | P a g e
Prepared by:1st Shift Students || Guided by : Dr.P.Kokila
B.Sc(CS) , LRG Govt.Arts College for wornen, Tirupur
C++ Class Notes,
UNIT-4
1.Introduction to pointer
2.Pointer declaration
3.Pointer to class and object
4.Pointer to base class and derived class
5.Array and characteristics
6.Array of class
7.Memory models
8.New and delete operation
9.Dynamic object
10.Binding Polymorphism and virtual function
POINTERS IN C++
Introduction to pointer
Pointers are symbolic representations of addresses. They enable programs to simulate call-by-
reference as well as to create and manipulate dynamic data structures. Iterating over elements in
arrays or other data structures is one of the main use of pointers.
The address of the variable you’re working with is assigned to the pointer variable that points to
the same data type (such as an int or string).
Syntax:
datatype *var_name; int *ptr; // ptr can point to an address which holds int data
Features of Pointers:
1. Pointers save memory space.
2. Execution time with pointers is faster because data are manipulated with the address, that
is, direct access to memory location.
3. Memory is accessed efficiently with the pointers. The pointer assigns and releases the
memory as well. Hence it can be said the Memory of pointers is dynamically allocated.
4. Pointers are used with data structures. They are useful for representing two-dimensional
and multi-dimensional arrays.
5. An array, of any type, can be accessed with the help of pointers, without considering its
subscript range.
6. Pointers are used for file handling.
7. Pointers are used to allocate memory dynamically.
8. In C++, a pointer declared to a base class could access the object of a derived class.
However, a pointer to a derived class cannot access the object of a base class.
89 | P a g e
Prepared by:1st Shift Students || Guided by : Dr.P.Kokila
B.Sc(CS) , LRG Govt.Arts College for wornen, Tirupur
C++ Class Notes,
Example:
Output:
Address of var1: 0x7fff5fbff8ac
Address of var2: 0x7fff5fbff8a8
Address of var3: 0x7fff5fbff8a4
Pointer Declaration
Pointers must be declared before they can be used, just like a normal variable. The syntax of
declaring a pointer is to place a * in front of the name. A pointer is associated with a type (such as
int and double ) too.
Pointer variable can be declared as below :
Syntax:
datatype *pointer variable
Example:
90 | P a g e
Prepared by:1st Shift Students || Guided by : Dr.P.Kokila
B.Sc(CS) , LRG Govt.Arts College for wornen, Tirupur
C++ Class Notes,
#include <iostream>
int main() {
// Declare and initialize a variable
int var = 20;
// Declare a pointer
int *ptr;
// Assign the address of var to ptr
ptr = &var;
// Print the value of var
std::cout << "Value of var: " << var << std::endl;
// Print the address stored in ptr
std::cout << "Address stored in ptr: " << ptr << std::endl;
// Print the value pointed to by ptr
std::cout << "Value pointed to by ptr: " << *ptr << std::endl;
// Modify the value pointed to by ptr
*ptr = 30;
// Print the updated value of var
std::cout << "Updated value of var: " << var << std::endl;
return 0;
}
Output:
Value of var: 20
Address stored in ptr: 0x7ffee0dd72dc
Value pointed to by ptr: 20
Updated value of var: 30
In this example:
1. We declare and initialize an integer variable var with the value 20.
2. We declare a pointer variable ptr of type integer.
3. We assign the address of var to ptr using the unary & operator.
4. We print the value of var, the address stored in ptr, and the value pointed to by ptr using the
dereference operator *.
5. We modify the value pointed to by ptr by assigning a new value to *ptr.
6. We print the updated value of var to demonstrate that modifying the value pointed to by ptr
affects the original variable var.
Void pointer
Pointer to object of any type can be implicitly converted to pointer to (possibly cv-qualified) void;
the pointer value is unchanged. The reverse conversion, which requires static_cast or explicit cast,
yields the original pointer value:
91 | P a g e
Prepared by:1st Shift Students || Guided by : Dr.P.Kokila
B.Sc(CS) , LRG Govt.Arts College for wornen, Tirupur
C++ Class Notes,
int n = 1 ;
int * p1 = & n ;
void * pv = p1 ;
int * p2 = static_cast < int *> ( pv ) ;
std::cou t << *p2 << '\n '; // prints 1
If the original pointer is pointing to a base class subobject within an object of some polymorphic
type, dynamic_cast may be used to obtain a void* that is pointing at the complete object of the
most derived type.
Pointers to void have the same size, representation and alignment as pointers to char.
Pointers to void are used to pass objects of unknown type, which is common in C interfaces:
std::malloc returns void*, std::qsort expects a user-provided callback that accepts two const void*
arguments. pthread_create expects a user-provided callback that accepts and returns void*. In all
cases, it is the caller's responsibility to cast the pointer to the correct type before use.
Wild pointer
Wild pointer in C is an uninitialized pointer, containing a random memory address that points to
an invalid or non-existent memory location. Therefore for C programmers, always initializing
pointers and avoiding leaving them uninitialized is extremely crucial.
Example:
/ C program that demonstrated wild pointers
int main()
{
/* wild pointer */
int* p;
/* Some unknown memory location is being corrupted.
This should never be done. */
*p = 12;
92 | P a g e
Prepared by:1st Shift Students || Guided by : Dr.P.Kokila
B.Sc(CS) , LRG Govt.Arts College for wornen, Tirupur
C++ Class Notes,
}
POINTER TO CLASS
A pointer to a class in C++ refers to a pointer that holds the memory address of an object of that
class. This allows you to manipulate or access the object indirectly, using the pointer to refer to
the object's members.
Key Details:
1. Pointer Declaration: A pointer to a class is declared by using the class name followed by *.
2. Dereferencing: You can access the members of the class object via the pointer using the -
> operator.
3. Dynamic Allocation: You can dynamically allocate an object and use a pointer to refer to it
using the new keyword.
Example:
#include <iostream>
class Person
{
public:
std::string name;
void greet()
{
std::cout << "Hello, my name is " << name << std::endl;
} };
int main()
{
Person person;
person.name = "John";
Person* ptr = &person;
ptr->greet();
return 0;
}
Output:
Hello, my name is John
POINTER TO OBJECT
A pointer is a variable that stores the memory address of another variable (or object) as its value.
A pointer aims to point to a data type which may be int, character, double, etc.
Pointers to objects aim to make a pointer that can access the object, not the variables. Pointer to
object in C++ refers to accessing an object.
There are two approaches by which you can access an object. One is directly and the other is by
using a pointer to an object in C++.
A pointer to an object in C++ is used to store the address of an object. For creating a pointer to
an object in C++, we use the following syntax:
93 | P a g e
Prepared by:1st Shift Students || Guided by : Dr.P.Kokila
B.Sc(CS) , LRG Govt.Arts College for wornen, Tirupur
C++ Class Notes,
Classname*pointertoobject;
For storing the address of an object into a pointer in c++, we use the following syntax:
pointertoobject=&objectname;
Key concepts:
1. Object Pointer: A pointer that holds the memory address of an object.
2. Arrow Operator (->): Used to access an object's members (both methods and attributes)
through a pointer.
3. Dynamic Memory Allocation: Using the new keyword to create objects dynamically on the
heap.
Example:
#include <iostream>
class Box
{
public:
int width = 10;
};
int main()
{
Box box;
Box* ptr = &box;
std::cout << ptr->width;
return 0;
}
Output:
10
THIS POINTER
In C++, ‘this’ pointers is a pointer to the current instance of a class. It is used to refer to the object
within its own member functions. In this article, we will learn how to use ‘this’ pointer in C++.
The ‘this’ pointer is passed as a hidden argument to all nonstatic member function calls and is
available as a local variable within the body of all nonstatic functions.
‘this’ pointer is not available in static member functions as static member functions can be called
without any object (with class name).
Even if only one member of each function exists which is used by multiple objects, the compiler
supplies an implicit pointer along with the names of the functions as ‘this’.
Example:
#include <iostream>
class Test
{
94 | P a g e
Prepared by:1st Shift Students || Guided by : Dr.P.Kokila
B.Sc(CS) , LRG Govt.Arts College for wornen, Tirupur
C++ Class Notes,
public:
int x;
void setX(int x)
{
this->x = x;
}
void printX()
{
std::cout << "x = " << this->x << std::endl;
}
};
int main()
{
Test t;
t.setX(10);
t.printX();
return 0;
}
Output:
x = 10
Approach:
95 | P a g e
Prepared by:1st Shift Students || Guided by : Dr.P.Kokila
B.Sc(CS) , LRG Govt.Arts College for wornen, Tirupur
C++ Class Notes,
• A derived class is a class that takes some properties from its base class.
• It is true that a pointer of one class can point to another class, but classes must be a base
and derived class, then it is possible.
• To access the variable of the base class, a base class pointer will be used.
• So, a pointer is a type of base class, and it can access all, public function and variables of
the base class since the pointer is of the base class, this is known as a binding pointer.
• In this pointer base class is owned by the base class but points to the derived class object.
• The same works with derived class pointer, values are changed.
Example:
#include <iostream>
// Base class
class Shape {
void public:
virtual draw() = 0; // Pure virtual function
};
// Derived class 1
class Circle : public Shape {
public:
void draw() override {
std::cout << "Drawing a circle." << std::endl;
}
};
// Derived class 2
class Rectangle : public Shape {
public:
void draw() override {
std::cout << "Drawing a rectangle." << std::endl;
}
};
int main() {
// Create objects of derived classes
Circle circle;
Rectangle rectangle;
// Pointer to base class
Shape *shapePtr;
// Point to derived class objects
shapePtr = &circle;
shapePtr->draw(); // Output: Drawing a circle.
shapePtr = &rectangle;
shapePtr->draw(); // Output: Drawing a rectangle.
return 0;
}
96 | P a g e
Prepared by:1st Shift Students || Guided by : Dr.P.Kokila
B.Sc(CS) , LRG Govt.Arts College for wornen, Tirupur
C++ Class Notes,
Output:
Drawing a circle.
Drawing a rectangle.
class BaseClass_Name{
//body of class
};
class DerivedClass_Name : access-specifier Baseclass_Name{ //body of class
};
1. A base class is an existing class from which the other A derived class is a class that is
classes are derived and inherit the methods and constructed from a base class or an
properties. existing class.
2. Base class can’t acquire the methods and properties Derived class can acquire the methods
of the derived class. and properties of the base class.
3. The base class is also called superclass or parent The derived class is also called a
class. subclass or child class.
ARRAYS
97 | P a g e
Prepared by:1st Shift Students || Guided by : Dr.P.Kokila
B.Sc(CS) , LRG Govt.Arts College for wornen, Tirupur
C++ Class Notes,
In C++, an array is a data structure that is used to store multiple values of similar data types in a
contiguous memory location.
For example, if we have to store the marks of 4 or 5 students then we can easily store them by
creating 5 different variables but what if we want to store marks of 100 students or say 500
students then it becomes very challenging to create that numbers of variable and manage them.
Now, arrays come into the picture that can do it easily by just creating an array of the required
size.
data_type array_name[Size_of_array];
Example
int arr[5];
Initialization of Array
In C++, we can initialize an array in many ways but we will discuss some most common ways to
initialize an array. We can initialize an array at the time of declaration or after declaration.
98 | P a g e
Prepared by:1st Shift Students || Guided by : Dr.P.Kokila
B.Sc(CS) , LRG Govt.Arts College for wornen, Tirupur
C++ Class Notes,
Syntax:
Example
int arr[5] = {1, 2, 3, 4, 5};
Characteristics
• An Array is a collection of data of the same data type, stored at a contiguous memory
location.
• Indexing of an array starts from 0. It means the first element is stored at the 0th index, the
second at 1st, and so on.
• Elements of an array can be accessed using their indices.
• Once an array is declared its size remains constant throughout the program.
• An array can have multiple dimensions.
• The size of the array in bytes can be determined by the sizeof operator using which we can
also find the number of elements in the array.
• We can find the size of the type of elements stored in an array by subtracting adjacent
addresses.
Array of class
The introduction of array class from C++11 has offered a better alternative for C-style arrays.
The advantages of array class over C-style array are :-
• Array classes knows its own size, whereas C-style arrays lack this property. So when passing
to functions, we don’t need to pass size of Array as a separate parameter.
• With C-style array there is more risk of array being decayed into a pointer. Array classes
don’t decay into pointers
• Array classes are generally more efficient, light-weight and reliable than C-style arrays.
Operations on array :-
1. at() :- This function is used to access the elements of array.
2. get() :- This function is also used to access the elements of array. This function is not the
member of array class but overloaded function from class tuple.
3. operator[] :- This is similar to C-style arrays. This method is also used to access array
elements.
4. front() :- This returns reference to the first element of array.
5. back() :- This returns reference to the last element of array.
6. size() :- It returns the number of elements in array. This is a property that C-style arrays
lack.
7. max_size() :- It returns the maximum number of elements array can hold
i.e, the size with which array is declared. The size() and max_size() return the same value.
8. swap() :- The swap() swaps all elements of one array with other.
99 | P a g e
Prepared by:1st Shift Students || Guided by : Dr.P.Kokila
B.Sc(CS) , LRG Govt.Arts College for wornen, Tirupur
C++ Class Notes,
9. empty() :- This function returns true when the array size is zero else returns false.
10.fill() :- This function is used to fill the entire array with a particular value.
Example:
// C++ code to demonstrate working of array,
// at() and get()
#include<iostream>
#include<array> // for array, at()
#include<tuple> // for get()
using namespace std;
int main()
{
// Initializing the array elements
array<int,6> ar = {1, 2, 3, 4, 5, 6};
// Printing array elements using at()
cout << "The array elements are (using at()) : ";
for ( int i=0; i<6; i++)
cout << ar.at(i) << " ";
cout << endl;
// Printing array elements using get()
cout << "The array elements are (using get()) : ";
cout << get<0>(ar) << " " << get<1>(ar) << " ";
cout << get<2>(ar) << " " << get<3>(ar) << " ";
cout << get<4>(ar) << " " << get<5>(ar) << " ";
cout << endl;
// Printing array elements using operator[]
cout << "The array elements are (using operator[]) : ";
for ( int i=0; i<6; i++)
cout << ar[i] << " ";
cout << endl;
return 0;
}
Output:
The array elements are (using at()) : 1 2 3 4 5 6
The array elements are (using get()) : 1 2 3 4 5 6
The array elements are (using operator[]) : 1 2 3 4 5 6
MEMORY MODELS
Memory Model is a specification that describes how the program interacts with the memory. In
C++ 11, a standardized memory model is created to provide the solution to issues surrounding
concurrency, ordering, and multithreading. This framework specifies how memory is accessed and
arranged in a C++ program. In this article, we will discuss the C++ 11 memory model, its features,
and advantages.
100 | P a g e
Prepared by:1st Shift Students || Guided by : Dr.P.Kokila
B.Sc(CS) , LRG Govt.Arts College for wornen, Tirupur
C++ Class Notes,
NEW OPERATOR
The new operator denotes a request for memory allocation on the Free Store. If sufficient memory
is available, a new operator initializes the memory and returns the address of the newly allocated
and initialized memory to the pointer variable.
Syntax to use new operator
pointer-variable = new data-type;
Here, the pointer variable is the pointer of type data-type. Data type could be any built-in data
type including array or any user-defined data type including structure and class.
Example:
// Pointer initialized with NULL
// Then request memory for the variable
int *p = NULL;
p = new int;
OR
// Combine declaration of pointer
// and their assignment int *p = new int;
Initialize memory:
We can also initialize the memory for built-in data types using a new operator. For custom data
types, a constructor is required (with the data type as input) for initializing the value. Here’s an
example of the initialization of both data types :
delete operator
Since it is the programmer’s responsibility to deallocate dynamically allocated memory,
programmers are provided delete operator in C++ language.
101 | P a g e
Prepared by:1st Shift Students || Guided by : Dr.P.Kokila
B.Sc(CS) , LRG Govt.Arts College for wornen, Tirupur
C++ Class Notes,
Syntax:
// Release memory pointed by pointer-variable delete pointer-variable;
Here, the pointer variable is the pointer that points to the data object created by new.
Examples:
delete p; delete q;
To free the dynamically allocated array pointed by pointer variable, use the following form of
delete.
Example:
// It will free the entire array
// pointed by p.
delete[] p;
DYNAMIC OBJECT
In C++, the objects can be created at run-time. C++ supports two operators new and delete to
perform memory allocation and de-allocation. These types of objects are called dynamic objects.
The new operator is used to create objects dynamically and the delete operator is used to delete
objects dynamically. The dynamic objects can be created with the help of pointers.
Syntax:
1.ClassName *ptr_obj; // pointer to object
2.ptr_obj = new ClassName // Dynamic object creation
3.delete ptr_obj; // Delete object dynamically
Example:
class Test
{
public:
Test()
{ std::cout << "Dynamic object created";
}
};
int main()
{
Test* obj = new Test();
delete obj;
return 0;
}
Output:
Dynamic object created
102 | P a g e
Prepared by:1st Shift Students || Guided by : Dr.P.Kokila
B.Sc(CS) , LRG Govt.Arts College for wornen, Tirupur
C++ Class Notes,
man at the same time is a father, a husband, and an employee. So the same person exhibits
different behavior in different situations. This is called polymorphism. Polymorphism is considered
one of the important features of Object-Oriented Programming.
Types of Polymorphism
• Compile-time Polymorphism
• Runtime Polymorphism
1.Compile-Time Polymorphism
This type of polymorphism is achieved by function overloading or operator overloading.
A.Function Overloading
When there are multiple functions with the same name but different parameters, then the
functions are said to be overloaded, hence this is known as Function Overloading. Functions can
be overloaded by changing the number of arguments or/and changing the type of arguments. In
simple terms, it is a feature of object-oriented programming providing many functions that have
the same name but distinct parameters when numerous tasks are listed under one function name.
There are certain Rules of Function Overloading that should be followed while overloading a
function.
B.Operator Overloading
C++ has the ability to provide the operators with a special meaning for a data type, this ability is
known as operator overloading. For example, we can make use of the addition operator (+) for
string class to concatenate two strings. We know that the task of this operator is to add two
operands. So a single operator ‘+’, when placed between integer operands, adds them and when
placed between string operands, concatenates them.
2. Runtime Polymorphism
This type of polymorphism is achieved by Function Overriding. Late binding and dynamic
polymorphism are other names for runtime polymorphism. The function call is resolved at
runtime in runtime polymorphism. In contrast, with compile time polymorphism, the compiler
determines which function call to bind to the object after deducing it at runtime.
A.Function Overriding
103 | P a g e
Prepared by:1st Shift Students || Guided by : Dr.P.Kokila
B.Sc(CS) , LRG Govt.Arts College for wornen, Tirupur
C++ Class Notes,
Function Overriding occurs when a derived class has a definition for one of the member functions
of the base class. That base function is said to be overridden.
Runtime Polymorphism with Data Members
Runtime Polymorphism cannot be achieved by data members in C++. Let’s see an example where
we are accessing the field by reference variable of parent class which refers to the instance of the
derived class.
Virtual Function
A virtual function is a member function that is declared in the base class using the keyword virtual
and is re-defined (Overridden) in the derived class.
The idea is that virtual functions are called according to the type of the object instance pointed to
or referenced, not according to the type of the pointer or reference.
In other words, virtual functions are resolved late, at runtime.
4. The prototype of virtual functions should be the same in the base as well as the derived
class.
5. They are always defined in the base class and overridden in a derived class. It is not
mandatory for the derived class to override (or re-define the virtual function), in that case, the
base class version of the function is used.
6. A class may have a virtual destructor but it cannot have a virtual constructor.
Example:
// C++ program to illustrate
// concept of Virtual Functions
#include <iostream>
using namespace std;
class base
{
104 | P a g e
Prepared by:1st Shift Students || Guided by : Dr.P.Kokila
B.Sc(CS) , LRG Govt.Arts College for wornen, Tirupur
C++ Class Notes,
public:
virtual void print()
{
cout << "print base class\n";
}
void show()
{
cout << "show base class\n";
}
};
class derived : public base
{
public:
void print()
{
cout << "print derived class\n";
}
void show()
{
cout << "show derived class\n";
}
};
int main()
{
base* bptr;
derived d;
bptr = &d;
// Virtual function, binded at runtime
bptr->print();
// Non-virtual function, binded at compile time
bptr->show();
return 0;
}
Output
print derived class
show base class
105 | P a g e
Prepared by:1st Shift Students || Guided by : Dr.P.Kokila
B.Sc(CS) , LRG Govt.Arts College for wornen, Tirupur
C++ Class Notes,
106 | P a g e
Prepared by:1st Shift Students || Guided by : Dr.P.Kokila
B.Sc(CS) , LRG Govt.Arts College for wornen, Tirupur
C++ Class Notes,
UNIT-5
1.File
2.File stream classes
3.File moses
4.Sequential read and write operation
5.Binary and Ascii files
6.Random access operation
7.Template
8.Exception handling
9.String
10.Declarion and initializing string object
11.String attributes
12.Miscellaneous function
FILES
A file is a named collection of data stored on a storage device, such as a hard drive, SSD, USB
drive, or CD/DVD. It's the fundamental unit of storage in a computer system. Think of it like a
container that holds information.
Here's a breakdown of what a file is and its key aspects:
Key Characteristics of a File:
* Name: Every file has a unique name within its directory (folder). The name helps you identify
and access the file. File names often have extensions (e.g., .txt, .jpg, .pdf) that indicate the file
type.
* Data: A file contains data, which can be anything from text and images to program instructions
and video. The type of data determines the file's format.
* Location: Files are stored in specific locations on the storage device, organized into directories
(folders). The file's path specifies its exact location within the file system.
* Size: The size of a file indicates how much storage space it occupies, usually measured in bytes,
kilobytes (KB), megabytes (MB), gigabytes (GB), etc.
* Attributes: Files have attributes associated with them, such as:
* Creation date and time: When the file was created.
* Modification date and time: When the file was last changed.
* Permissions: Who has access to the file and what they can do (read, write, execute).
* File type: The kind of data the file contains.
Types of Files:
Files can be broadly categorized into:
* Text files: Contain human-readable text, typically organized into lines. Examples include .txt,
.html, .cpp files.
* Binary files: Contain data in a format that is not directly human-readable. They are typically
used to store images, audio, video, executable programs, and other types of data. Examples
include .jpg, .mp3, .exe, .pdf files.
107 | P a g e
Prepared by:1st Shift Students || Guided by : Dr.P.Kokila
B.Sc(CS) , LRG Govt.Arts College for wornen, Tirupur
C++ Class Notes,
* Executable files: Contain instructions that can be executed by the computer's processor. They
are programs that perform specific tasks.
* Data files: Store data used by applications. They can be in various formats, such as databases,
spreadsheets, or configuration files.
File Operations:
You can perform various operations on files, including:
* Creating: Making a new file.
* Opening: Accessing an existing file.
* Reading: Retrieving data from a file.
* Writing: Storing data into a file.
* Appending: Adding data to the end of a file.
* Deleting: Removing a file.
* Renaming: Changing the name of a file.
* Copying: Creating a duplicate of a file.
* Moving: Changing the location of a file.
File Systems:
A file system is the way an operating system organizes and manages files on a storage device. It
defines how files are named, stored, accessed, and managed. Different operating systems use
different file systems (e.g., NTFS on Windows, ext4 on Linux, APFS on macOS).
Importance of Files:
Files are essential for storing and managing data on computers. They allow us to:
108 | P a g e
Prepared by:1st Shift Students || Guided by : Dr.P.Kokila
B.Sc(CS) , LRG Govt.Arts College for wornen, Tirupur
C++ Class Notes,
1. ios:-
ios stands for input output stream.
This class is the base class for other classes in this class hierarchy.
This class contains the necessary facilities that are used by all the other derived classes for input
and output operations.
2. istream:-
istream stands for input stream.
This class is derived from the class ‘ios’.
This class handle input stream.
The extraction operator(>>) is overloaded in this class to handle input streams from files to the
program execution.
This class declares input functions such as get(), getline() and read().
3. ostream:-
ostream stands for output stream.
This class is derived from the class ‘ios’.
This class handle output stream.
The insertion operator(<<) is overloaded in this class to handle output streams to files from the
program execution.
This class declares output functions such as put() and write().
4. streambuf:-
This class contains a pointer which points to the buffer which is used to manage the input and
output streams.
5. fstreambase:-
This class provides operations common to the file streams. Serves as a base for fstream, ifstream
and ofstream class.
109 | P a g e
Prepared by:1st Shift Students || Guided by : Dr.P.Kokila
B.Sc(CS) , LRG Govt.Arts College for wornen, Tirupur
C++ Class Notes,
In C++, files are mainly dealt by using three classes fstream, ifstream, ofstream available in
fstream headerfile.
• ofstream: Stream class to write on files
• ifstream: Stream class to read from files
• fstream: Stream class to both read and write from/to files.
110 | P a g e
Prepared by:1st Shift Students || Guided by : Dr.P.Kokila
B.Sc(CS) , LRG Govt.Arts College for wornen, Tirupur
C++ Class Notes,
111 | P a g e
Prepared by:1st Shift Students || Guided by : Dr.P.Kokila
B.Sc(CS) , LRG Govt.Arts College for wornen, Tirupur
C++ Class Notes,
Example (Complete):
#include <iostream>
#include <fstream>
#include <string>
int main() {
std::ofstream myFile("my_output.txt"); // Open for writing
if (myFile.is_open()) {
myFile << "This is some text.\n";
int number = 42;
myFile << "The answer is: " << number << std::endl;
myFile.close(); // Close the file
std::cout << "Data written to file." << std::endl;
} else {
std::cerr << "Error opening file!" << std::endl;
return 1; // Indicate an error
}
// Now read from the file:
std::ifstream inFile("my_output.txt");
if (inFile.is_open()) {
std::string line;
while (std::getline(inFile, line)) {
112 | P a g e
Prepared by:1st Shift Students || Guided by : Dr.P.Kokila
B.Sc(CS) , LRG Govt.Arts College for wornen, Tirupur
C++ Class Notes,
Related resources
File Handling in C++: Learn how to open files for reading and writing in C++
113 | P a g e
Prepared by:1st Shift Students || Guided by : Dr.P.Kokila
B.Sc(CS) , LRG Govt.Arts College for wornen, Tirupur
C++ Class Notes,
File Opening Modes: Learn about different file opening modes in C++
File Handling through C++ Classes: Learn about file modes in C++ using classes
Sequential read and write operations on files refer to accessing data in a linear, one-after-the-
other manner, starting from the beginning of the file and proceeding towards the end. It's like
reading a book from page one to the last page.
114 | P a g e
Prepared by:1st Shift Students || Guided by : Dr.P.Kokila
B.Sc(CS) , LRG Govt.Arts College for wornen, Tirupur
C++ Class Notes,
115 | P a g e
Prepared by:1st Shift Students || Guided by : Dr.P.Kokila
B.Sc(CS) , LRG Govt.Arts College for wornen, Tirupur
C++ Class Notes,
outputFile.put('C');
outputFile.put('\n');
outputFile.close();
}
return 0;
}
get() (istream):
The get() function comes in a few forms, all used for reading single characters from an input
stream:
* int get(); (No parameters):
Reads a single character from the input stream.
* Return value: The character read as an int. Returns EOF (usually -1) if the end of the file or
an error is encountered. It's very important to check for EOF when using this version of get().
* istream& get(char& c); (Character parameter):
Reads a single character and stores it in the char variable c.
* Return value: The istream object itself (allowing for chaining). The stream's state will be set
if an error occurs or the end of the file is reached. You can use the stream's boolean context to
check the status (e.g., if (myFile.get(ch)) { ... }).
* istream& get(char* s, streamsize n, char delim); (Character array, size, delimiter):
Reads characters from the input stream and stores them in the character arrays.
* n: The maximum number of characters to read (including the null terminator).
* delim: The delimiter character. Reading stops when this character is encountered (or when n
- 1 characters have been read or the end of the file is reached).
* A null terminator (\0) is automatically added to the end of the string in s.
* Return value: The istream object.
Examples (get()):
#include <iostream>
#include <fstream>
int main() {
// Using get() with cin (no parameters):
int ch;
std::cout << "Enter some characters (press Ctrl+D or Ctrl+Z to end):\n";
while ((ch = std::cin.get()) != EOF) {
std::cout.put(ch); // Echo the character
}
std::cout << "\nEnd of input.\n";
116 | P a g e
Prepared by:1st Shift Students || Guided by : Dr.P.Kokila
B.Sc(CS) , LRG Govt.Arts College for wornen, Tirupur
C++ Class Notes,
117 | P a g e
Prepared by:1st Shift Students || Guided by : Dr.P.Kokila
B.Sc(CS) , LRG Govt.Arts College for wornen, Tirupur
C++ Class Notes,
118 | P a g e
Prepared by:1st Shift Students || Guided by : Dr.P.Kokila
B.Sc(CS) , LRG Govt.Arts College for wornen, Tirupur
C++ Class Notes,
* ASCII files are a subset of binary files that use the ASCII encoding to represent characters.
* Choose binary files for efficiency and when storing non-text data.
* Choose ASCII files when human readability and portability are important.
You can read and write class objects to files in C++ using several methods. Here's a breakdown of
the common approaches, along with explanations and best practices:
1. Text-Based Approach (Human-Readable):
This method is suitable for simple classes and when human readability is desired. You essentially
convert the object's data members into text and write them to the file, and then reverse the
process when reading.
#include <iostream>
#include <fstream>
#include <string>
class Person {
public:
std::string name;
int age;
119 | P a g e
Prepared by:1st Shift Students || Guided by : Dr.P.Kokila
B.Sc(CS) , LRG Govt.Arts College for wornen, Tirupur
C++ Class Notes,
120 | P a g e
Prepared by:1st Shift Students || Guided by : Dr.P.Kokila
B.Sc(CS) , LRG Govt.Arts College for wornen, Tirupur
C++ Class Notes,
int age;
// ... (other methods)
// Method to write to binary file
bool writeToFile(std::ofstream& ofs) const {
size_t nameLen = name.length();
if (!ofs.write(reinterpret_cast<const char*>(&nameLen), sizeof(nameLen))) return false; //
Write string length
if (!ofs.write(name.c_str(), nameLen * sizeof(char))) return false; // Write String content
if (!ofs.write(reinterpret_cast<const char*>(&age), sizeof(age))) return false;
return true;
}
// Method to read from binary file
bool readFromFile(std::ifstream& ifs) {
size_t nameLen;
if (!ifs.read(reinterpret_cast<char*>(&nameLen), sizeof(nameLen))) return false;
name.resize(nameLen); // Important: Resize the string
if (!ifs.read(&name[0], nameLen * sizeof(char))) return false;
if (!ifs.read(reinterpret_cast<char*>(&age), sizeof(age))) return false;
return true;
}
};
int main() {
Person person1 = {"Bob", 40};
// Write to binary file:
std::ofstream outFile("people.dat", std::ios::binary);
if (outFile.is_open()) {
if (!person1.writeToFile(outFile)) {
std::cerr << "Error writing to file." << std::endl;
}
outFile.close();
}
// Read from binary file:
Person person2;
std::ifstream inFile("people.dat", std::ios::binary);
if (inFile.is_open()) {
if (!person2.readFromFile(inFile)) {
std::cerr << "Error reading from file." << std::endl;
}
std::cout << "Name: " << person2.name << ", Age: " << person2.age << std::endl;
inFile.close();
}
121 | P a g e
Prepared by:1st Shift Students || Guided by : Dr.P.Kokila
B.Sc(CS) , LRG Govt.Arts College for wornen, Tirupur
C++ Class Notes,
return 0;}
Advantages:
* More efficient than text-based for complex objects.
* Preserves data types precisely.
Disadvantages:
* Not human-readable.
* Less portable (endianness, compiler differences can be an issue).
* Changes to the class structure require careful handling to maintain compatibility.
3. Serialization Libraries (For Complex Objects):
For very complex classes or when portability is a major concern, using a serialization library is
often the best approach. These libraries handle the complexities of converting objects to a byte
stream and back. Popular choices include:
* Boost.Serialization: A powerful and widely used library.
* Cereal: A modern and efficient header-only library.
Example (using Cereal):
#include <iostream>
#include <fstream>
#include <string>
#include <cereal/archives/binary.hpp> // Or text, xml, etc.
#include <cereal/types/string.hpp>
#include <cereal/types/polymorphic.hpp> // If needed
class Person {
public:
std::string name;
int age;
122 | P a g e
Prepared by:1st Shift Students || Guided by : Dr.P.Kokila
B.Sc(CS) , LRG Govt.Arts College for wornen, Tirupur
C++ Class Notes,
// Read:
Person person2;
std::ifstream ifs("people.cereal", std::ios::binary);
{
cereal::BinaryInputArchive iar(ifs);
iar(person2);
}
std::cout << "Name: " << person2.name << ", Age: " << person2.age << std::endl;
return 0;
}
Choosing the Right Method:
* Simple classes, human readability: Text-based approach.
* Complex classes, efficiency, less concern for portability: Binary approach.
* Complex classes, portability, maintainability: Serialization library.
Remember to always handle potential file I/O errors (file not found, etc.) and consider versioning
if you anticipate changes to your classes over time. Serialization libraries often provide
mechanisms for versioning.
Random Access Operation:
Random access in C++ allows you to read and write data at specific positions in a file, rather than
sequentially from start to finish. This is especially useful when working with large files or when
you need to access data at various points without reading everything beforehand.
Key Concepts:
Random access means you can move the file pointer to any position within the file, allowing you
to read or write data at that position.
Example: Random Access in C++
This program demonstrates how to use random access to read and write data at specific positions
in a binary file.
Code:
#include <iostream> #include <fstream> struct Data { int id;
double value;
};
int main() {
// Writing to a binary file with random access
std::ofstream outFile("random_access.dat",
std::ios::binary);
if (!outFile) { std::cerr << "Error opening file for writing." << std::endl; return 1;
}
// Data to write into the file
Data data1 = {1, 3.14};
Data data2 = {2, 2.71};
Data data3 = {3, 1.61};
123 | P a g e
Prepared by:1st Shift Students || Guided by : Dr.P.Kokila
B.Sc(CS) , LRG Govt.Arts College for wornen, Tirupur
C++ Class Notes,
124 | P a g e
Prepared by:1st Shift Students || Guided by : Dr.P.Kokila
B.Sc(CS) , LRG Govt.Arts College for wornen, Tirupur
C++ Class Notes,
{
return (x > y) ? x : y;
}
int main()
{
// Call myMax for int cout << myMax<int>(3, 7) << endl; // call myMax for double cout <<
myMax<double>(3.0, 7.0) << endl;
// call myMax for char cout << myMax<char>('g', 'e') << endl;
return 0;
}
Output
77g
Exception Handling:
In C++, exceptions are runtime anomalies or abnormal conditions that a program encounters
during its execution. The process of handling these exceptions is called exception handling. Using
the exception handling mechanism, the control from one part of the program where the
exception occurred can be transferred to another part of the code.
Types of C++ Exception:
There are two types of exceptions in C++
Synchronous: Exceptions that happen when something goes wrong because of a mistake in the
input data or when the program is not equipped to handle the current type of data it’s working
with, such as dividing a number by zero.
Asynchronous: Exceptions that are beyond the program’s control, such as disc failure, keyboard
interrupts, etc
C++ try and catch
C++ provides an inbuilt feature for Exception Handling. It can be done using the following
specialized keywords: try, catch, and throw with each having a different purpose.
Example program :
// C++ program to demonstate the use of try,catch and throw
// in exception handling.
#include <iostream> #include <stdexcept> using namespace std; int main()
{
// try block
try {
int numerator = 10; int denominator = 0; int res;
// check if denominator is 0 then throw runtime
// error.
if (denominator == 0) {
throw runtime_error(
"Division by zero not allowed!");
125 | P a g e
Prepared by:1st Shift Students || Guided by : Dr.P.Kokila
B.Sc(CS) , LRG Govt.Arts College for wornen, Tirupur
C++ Class Notes,
}
// calculate result if no exception occurs res = numerator / denominator;
//[printing result after division cout << "Result after division: " << res << endl;
}
// catch block to catch the thrown exception catch (const exception& e) { // print the exception
cout << "Exception " << e.what() << endl;
}
return 0;
}
Output
Exception Division by zero not allowed!.
String
C++ strings are sequences of characters stored in a char array. Strings are used to store words
and text. They are also used to store data, such as numbers and other types of information.
Strings in C++ can be defined either using the std::string
class or the C-style character arrays.
Strings in C++
126 | P a g e
Prepared by:1st Shift Students || Guided by : Dr.P.Kokila
B.Sc(CS) , LRG Govt.Arts College for wornen, Tirupur
char s[] = "GeeksforGeeks"; cout << s << endl;
return 0;
}
Output
GeeksforGeeks
2. std::string Class:
These are the new types of strings that are introduced in C++ as std::string class defined inside
<string> header file. This provides many advantages over conventional C-style strings such as
dynamic size, member functions, etc. Syntax:
std::string str("GeeksforGeeks");
// C++ program to create std::string objects
#include <iostream> using namespace std;
int main()
{
string str("GeeksforGeeks");
cout << str; return 0;
}
Output:
GeeksforGeeks
Declaring and Initializing
String Object:
In C++, strings can be declared and initialized using the std::string class, which is part of the
C++ Standard Library. Unlike C-style strings (character arrays), the std::string class provides a
variety of built-in functions that simplify string manipulation, making it a safer and more
flexible option.
Declaration and Initialization of String: Syntax: std::string company = "GeeksforGeeks!";
Initializing a String in C++:
1. char str[] = "Geeks";
2. char str[6] = "Geeks";
3. char str[] = {'G', 'e', 'e', 'k', 's', '\0'};
4. char str[6] = {'G', 'e', 'e', 'k', 's', '\0'};
Below is the memory representation of the string “Geeks” in C++. strings in c++cout << str;
return 0;
}
Output:
Geeks
String Attributes:
The [string] attribute indicates that the one-dimensional char, wchar_t, byte (or equivalent)
array or the pointer to such an array must be treated as a string. The string can also be an
array (or a pointer to an array) of constructs whose fields are all of the type byte.
syntax: typedef [ string [[ , type-attribute-list ]] ] type-specifier declarator-list; typedef [ struct
| union ]
{
[ string [[ , field-attribute-list ]] ] type-specifier declarator-list;
127 | P a g e
Prepared by:1st Shift Students || Guided by : Dr.P.Kokila
B.Sc(CS) , LRG Govt.Arts College for wornen, Tirupur
...
};
Example program:
#include <iostream>
#include <string>
class Book {
private:
// String attributes for title and author
std::string title; std::string author;
public:
// Constructor to initialize title and author
Book(std::string t, std::string a) { title = t;
author = a;
}
// Method to display book details void displayDetails() {
std::cout << "Title: " << title << std::endl; std::cout << "Author: " << author << std::endl;
}
};
int main() {
// Create a Book object with initial values for title and author Book book1("The Catcher in the
Rye", "J.D. Salinger");
// Display book details book1.displayDetails();
return 0;
}
Output:
Title: The Catcher in the Rye
Author: J.D. Salinger
Miscellaneous Functions:
Miscellaneous functions perform a variety of operations and return specific information or
values. The miscellaneous functions are summarized in the table below. Click the function
name to jump to a discussion of that function.
Miscellaneous functions perform a variety of operations and return specific information or
values. The miscellaneous functions are summarized in the table below. Click the function
name to jump to a discussion of that function.
Function and results
Always: used as a placeholder or stub
Call:suspend one calculation and execute another calculation fie
Chain: calls another calculation language file
CFind: Temporarily suspends one calculation and execute another calculation file
CPSTR: Convert a string constant, or any value from a string variable, to a specific codepage
number.
DECLARE: Create a DAL variable as an integer variable, decimal variable, or string variable and
optionally assign it a codepage value.
Exists: Determine if a DAL symbolic variable exist
128 | P a g e
Prepared by:1st Shift Students || Guided by : Dr.P.Kokila
B.Sc(CS) , LRG Govt.Arts College for wornen, Tirupur
GetLocale:
Get value: Returns a string that contains the contents of the DAL symbolic variable specified
by the parameter.
LoadLib: Loads a file that contains a library of DAL scripts.
Majoversion: Retrieves the major version number of the system being executed.
Minor version: Retrieves the minor version number of the system being executed.
Print_it: Prints a string on the console.
Retain: Retains DAL variables during transaction processing.
SetLocale:Assign a new locale definition.
UniqueString
Unique string: a 45-character globally unique string.
129 | P a g e
Prepared by:1st Shift Students || Guided by : Dr.P.Kokila
B.Sc(CS) , LRG Govt.Arts College for wornen, Tirupur
Question Bank
130 | P a g e
Prepared by:1st Shift Students || Guided by : Dr.P.Kokila
B.Sc(CS) , LRG Govt.Arts College for wornen, Tirupur
Powered by TCPDF (www.tcpdf.org)