C++ Programming
C++ Programming
Fundamental Concepts:
1. Instructions: Instruction is nothing but meaningfully written statement using a programming
language. It is a command to processor to perform an action/operation.
2. Computer Languages:
Language that is used to communicate with the machines to build softwares is called computer
languages.
Machine Level Language (MLL): Instructions are represented by the combination of 0‘s
and 1‘s. MLL is called as first generation language. MLL do not need translators since it
can be directly operated on the machines.
E.g., 1001 10101 1101.
Limitations of MLL:
Lack of readability- programs are difficult to write and read.
2. High level language: Instructions are represented in English like language. They are
considered as high level language because it is very much closer to the human languages.
E.g., C, C++, JAVA, C#, PHP etc.
4. Language Translator:
Since machines understand only machine level instructions, the programs written in ALL or HLL
needs to be converted or translated to machine understandable form. This translation is done by
language translators.
Types of Translators:
Page 1 of 27
Compiler: It translates high level language to machine level language whole program at
once.
E.g., Turbo C/C++ compiler.
Interpreter: It translates high level language to machine level language line by line.
E.g., Javascript, PHP interpreter.
Assembler: It translates assembly level language to machine level language.
E.g., Turbo Assembler
5. Software:
Set of programs is called as software. Software can be categorized into 2 types they are:
1. System software.
2. Application software.
System software: Software that manage the operations of the computer. System software
directly interacts with the hardware to make application programs operational.
E.g., Operating system, compilers, assemblers, Disk utility software, network settings
software, etc.
Page 2 of 27
b. User document: These are the documents designed for the sake of user to understand about
the software like user manuals.
7. Maintenance: In this stage any upgradation or modification or errors reported are taken
care.
These stages are often iterative, meaning the process may cycle back to earlier stages if issues or
new requirements arise during development.
1. Focus on Functions/Procedures:
o Each procedure performs a specific task and may be called multiple times
throughout the program.
2. Top-Down Approach:
o In POP, the design approach follows a top-down methodology, where the problem
is broken down into smaller sub-problems. The highest level of the problem is
addressed first, then refined into lower levels.
o This approach makes it easier to manage complex problems by tackling them step
by step.
o Data in POP is often shared among functions. Variables are defined globally, and
functions operate on this global data.
o This can lead to issues like data corruption if multiple procedures are trying to
manipulate the same data at once.
4. Sequential Execution:
Page 3 of 27
o Instructions or functions are executed in a predefined sequence. The program
follows a clear flow of control where functions are called one after another based
on the program logic.
5. Modularity:
o Code reuse is possible as functions can be reused across different parts of the
program.
6. No Data Encapsulation:
o POP is efficient for small programs where the focus is on simple tasks. It is less
suitable for large, complex systems, as it lacks mechanisms like data
encapsulation and abstraction that are crucial in OOP.
Examples of programming language that follows POP are C, PASCAL, COBOL, etc.
Advantages of POP:
Well-suited for tasks that can be easily broken down into steps.
Disadvantages of POP:
Page 4 of 27
Introduction to Object Oriented Programming
o Objects are instances of classes, which act as blueprints. A class defines the
attributes (data) and methods (functions) that the objects will have.
o Objects encapsulate the state (data) and behavior (methods) within a program.
o Example: In a class Car, objects could be car1, car2, etc., each representing a
specific car.
2. Encapsulation:
o Encapsulation is the bundling of data and methods that operate on that data
within a single unit (object).
o It restricts direct access to an object‘s data and only allows modifications through
its methods, promoting data security and preventing unauthorized access.
o Example: In a class BankAccount, only the account holder (via methods like
deposit or withdraw) can modify the balance.
3. Abstraction:
o It simplifies interaction with objects by exposing only what is necessary for the
user.
o Example: A Car class might expose methods like start and stop but hide complex
internal mechanisms like the engine's functioning.
4. Inheritance:
Page 5 of 27
o This promotes code reusability and hierarchical classification. Subclasses can add
new features or override existing ones.
o Example: A class Vehicle could have subclasses Car, Bike, and Truck, which
inherit common properties like no of tyres, speed and fuel but also have unique
features.
o Inheritance is called ―is a‖ relationship. The subclass "is-a" type of the superclass,
meaning it shares the common characteristics (attributes and methods) of the
parent but may also have additional, specialized features. For eg., Car is a Vehicle,
Bike is a Vehicle.
5. Polymorphism:
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
Page 6 of 27
Overloading. Functions can be overloaded by changing the number of arguments
or/and changing the type of arguments.
o Example: A method draw() might work differently for objects of classes Circle,
Rectangle, or Triangle, each having its own version of draw().
o NOTE: Runtime vs. compile time: Compile time is when programming code is
converted to machine code, while runtime is when a program is running. Runtime
generally occurs after compile time.
Operator Overloading
6. Dynamic Binding:
o Dynamic binding refers to the process where the method to be invoked is
determined at runtime, based on the object type.
Advantages of OOP:
Scalability: The modularity of OOP allows complex systems to be built from smaller,
independent objects.
Page 7 of 27
Disadvantages of OOP:
Complexity: OOP can be more complex to implement, especially for smaller programs
where procedural programming might be simpler.
Memory Overhead: The creation and management of objects require more system
resources compared to procedural programming.
Application of OOP:
6. CAD, CAM.
7. Multimedia application.
Examples of programming language that follows OOP are C++, JAVA, C#, Python, PHP, PERL,
RUBY, etc.
POP OOP
Page 8 of 27
4. Function transforms data from one form 4. Objects communicate with each other
to another. through functions.
Include files
Class declarations
Member functions definitions
Main Function
In C++, programs often follow an organized structure that includes include files, a class
declaration, member function definitions, and the main function. Here's a breakdown of
each section with examples:
1. Include Files
Include files, also known as preprocessor directives, are used to include external libraries
or files needed by the program. These libraries may contain predefined classes and
functions for tasks like input/output, mathematics, etc. This is done using the #include
directive.
E.g., #include <iostream> // Allows input/output operations
Page 10 of 27
#include <string> // Allows string operations
2. Class Declaration
The class declaration defines a class, which is a user-defined data type in C++ that
encapsulates data (attributes) and functions (methods) that operate on the data. This
declaration typically includes:
The member function definitions provide the actual implementation of the member
functions declared in the class. These are usually defined outside the class using the scope
resolution operator :: to indicate which class the function belongs to.
4. Main Function
The main function is the entry point of the C++ program, where the program begins
execution. Inside the main(), we can create objects of the class, call member functions, and
perform operations.
Note: Additional sections such as user defined function section, global declaration section
can also be included like in C language as C++ is superset of C.
#include<iostream>
class person
char name[10];
public:
void getdata(void);
void display(void);
};
Page 11 of 27
void person:: getdata(void)
cout<<―enter name‖;
cin>>name;
cout<<name;
int main()
person p;
p.getdata();
p.display();
return 0;
Note: Namespaces allows the grouping of different entities such as classes, objects, functions and
a variety of C++ tokens, etc., under a single name. It is used to avoid same name conflicts.
To use the classes, objects, etc of a namespace we should use scope resolution operator ―::‖.
Keywords in C++
Keywords are predefined reserved identifiers that have special meanings. They cannot be used
as identifiers in your program. There are 63 keywords in C++. The following are some of the
keywords in C++.
Page 12 of 27
Break case for if
class structure int continue
Identifiers
A C++ identifier is a name used to identify a variable, function, class, module, or any other user-
defined item.
Reserved words (like C++ keywords, such as int) cannot be used as names
Constants
When you do not want others (or yourself) to change existing variable values, use the const
keyword (this will declare the variable as "constant", which means unchangeable and read-only).
It is fixed value and do not change during the program execution.
For e.g.,
Comments in C++
Comments are used to increase the understandability enhancing readability of the code. Generally,
comments are written to help other coders, who are working on same application and want to
understand the code written by someone else.
Page 13 of 27
Variables
Variables are containers for storing data values. The value in the variable may be changed during
the program execution by the instructions.
In C++, there are different types of variables (defined with different keywords), for example:
int - stores integers (whole numbers), without decimals, such as 123 or -123
double - stores floating point numbers, with decimals, such as 19.99 or -19.99
char - stores single characters, such as 'a' or 'B'. Char values are surrounded by single quotes
string - stores text, such as "Hello World". String values are surrounded by double quotes
To create a variable, specify the type and mention the variable name. Initial value can be assigned
to the variable at the time of declaration.
Syntax
Where type is one of C++ types (such as int), and variableName is the name of the variable (such
as x or myName). The equal sign is used to assign values to the variable.
E.g.,
Note: Rules for naming a variable is same as rules for naming an identifier.
Data types
In C++, data types define the type of data that a variable can hold. Or it refers the category of the
variable. It defines the type of operations that can be performed on the data and also determine the
size and type of information stored in a variable. C++ provides several categories of data types,
including built-in (or primitive) types, user-defined types, and derived types. Here‘s an overview
of the main data types in C++:
Page 14 of 27
Category Data Type Description
Size: 1 byte.
Range: From -128 to 127 or 0 to 255 (depending on whether it‘s signed or unsigned).
Page 15 of 27
e. Void Type (void)
These types are based on primitive types and are created using them.
a. Arrays
b. Pointers
c. References
C++ allows users to create their own data types to suit specific needs.
a. Structures (struct)
Page 16 of 27
Description: A structure is a user-defined type that groups variables of different types
under a single name.
string name;
int age;
};
Person p1;
p1.name = "Mohan";
p1.age = 25;
b. Unions (union)
Description: A union is similar to a structure, but all members share the same memory
location. It can only store one value at a time.
E.g.,
union Data {
int intVal;
float floatVal;
};
Data data;
c. Enumerations (enum)
Description: Used to define a set of named integral constants. Each constant in an enum
is assigned a unique value.
Page 17 of 27
E.g.,
d. Classes
Description: A class is a user-defined data type that encapsulates data (attributes) and
functions (methods) that operate on the data. It is central to object-oriented programming
in C++. It is the blue print/template of object.
E.g.,
class Car {
string brand;
int year;
public:
void display() {
cout << "Brand: " << brand << ", Year: " << year;
};
Type Conversion
Type conversion in C++ is the process of converting one data type to another. C++ provides two
types of type conversions:
Implicit type conversion occurs when the compiler automatically converts one data type to another
without the programmer's intervention. This usually happens when mixing different data types in
expressions or assignments.
Page 18 of 27
E.g.,
int a = 10;
double b = 5.5;
C++ promotes smaller types to larger types when they are mixed.
In explicit type conversion, the programmer manually converts one data type to another using type
casting. C++ provides several ways to do type casting:
Syntax: type(expression);
E.g.,
int a = 10;
Operators
In C++, operators are symbols that perform operations on variables and values. These operators
can be categorized into different types based on their functionality. Here's an overview of the
various types of operators in C++:
1. Arithmetic Operators
+ Addition a+b
- Subtraction a–b
* Multiplication a*b
Page 19 of 27
Operator Description Example
/ Division a/b
% Modulus (Remainder) a % b
Relational operators are used to compare two values. The result is a boolean value (true or false).
== Equal to a == b
!= Not equal to a != b
E.g,
3. Logical Operators
Logical operators are used to combine multiple relational conditions. The result is also a boolean
value.
Page 20 of 27
Operator Description Example
|| Logical OR a || b
! Logical NOT !a
E.g.,
4. Assignment Operators
= Assign a=b
++ Increment by 1 ++a
-- Decrement by 1 --a
int a = 5;
6. Bitwise Operators
Bitwise operators perform operations at the bit level. These operators work on binary
representations of integers.
| | Bitwise OR
^ Bitwise XOR a ^ b
~ Bitwise NOT ~a
E.g,:
The ternary operator is a shorthand for if-else conditions. It takes three operands: a condition, a
result if true, and a result if false.
E.g.,
Page 22 of 27
9. Comma Operator
The comma operator , is used to separate multiple expressions, and it evaluates from left to right.
E.g.,
int a, b, c;
a = (b = 2, c = 3, b + c); // a = 5
E.g.,
int a = 10;
The scope resolution operator :: is used to define a function outside the class or to access a global
variable when there's a local variable with the same name.
E.g.,
int a = 10;
class Example {
public:
void display() {
};
Page 23 of 27
Note: scope resolution operator is used in defining member functions and using objects/identifiers
of namespaces.
The sizeof operator returns the size of a variable or data type in bytes.
E.g.,
int a;
The new operator dynamically allocates memory, and the delete operator frees the memory.
Example:
Precedence of operators
In C++, operator precedence determines the order in which operators are evaluated in expressions.
This affects how expressions are parsed and computed. Operators with higher precedence are
evaluated before operators with lower precedence. If two operators have the same precedence,
associativity rules determine their evaluation order.
o Parentheses (): Used to override the default precedence and specify the order of
evaluation.
Page 24 of 27
3. Relational Operators
o == (equal to), != (not equal to), > (greater than), < (less than), >= (greater than or
equal to), <= (less than or equal to)
4. Logical Operators
o Logical OR: ||
5. Assignment Operators
6. Bitwise Operators
o Bitwise XOR: ^
o Bitwise OR: |
7. Conditional Operator
o ? : (ternary conditional)
8. Comma Operator
Associativity
Associativity defines the order of operations for operators with the same precedence level:
Left-to-Right: Most operators, including arithmetic, relational, and bitwise operators, are
evaluated from left to right.
E.g.,
int a = 5;
int b = 10;
Page 25 of 27
int c = 15;
int result = a + b * c; // Multiplication (*) has higher precedence than addition (+)
Expressions
In C++, expressions are combinations of variables, constants, operators, and functions that
evaluate to a value. They are fundamental to writing programs, as they perform calculations, make
decisions, and control the flow of the program. Here‘s a detailed explanation of different types of
expressions in C++:
1. Arithmetic Expressions
Arithmetic expressions use arithmetic operators to perform mathematical operations. They operate
on numeric values and variables.
Relational expressions compare two values and return a boolean result (true or false).
E.g.,
int a = 10;
int b = 20;
3. Logical Expressions
Logical expressions combine boolean values or relational expressions using logical operators.
E.g.,
bool a = true;
bool b = false;
4. Assignment Expressions
Assignment expressions assign a value to a variable and return the assigned value.
E.g.,
Page 26 of 27
int c,a = 10,b =5;
Storage Classes: It provides the information about variable visibility or scope, lifetime and storage
location. There are 4 types of storage classes they are:
Page 27 of 27
VISION OF THE INSTITUTE
Empower the individuals and society at large through educational excellence; sensitize them for
a life dedicated to the service of fellow human beings and mother land.
To impact holistic education that enables the students to become socially responsive and useful,
with roots firm on traditional and cultural values; and to hone their skills to accept challenges
and respond to opportunities in a global scenario.
BT
CO’s DESCRIPTION OF THE OUTCOMES
LEVEL
Understand the fundamental concepts and benefits of Object-Oriented
1 Programming (OOP) and how it differs from Procedure-Oriented L2
Programming paradigms.
Interpret and apply C++ syntax and structure, including input-output
statements, keywords, identifiers, constants, variables, data types,
2 L3
operators, expressions and file handling to create basic programs and
solve problems
Describe the control structures, functions, and different parameter
3 L3
passing methods and write programs to solve problems.
Demonstrate the concepts of classes and objects , access specifiers,
4 constructors, destructors, and OOP features like polymorphism, L3
inheritance with the help of programs.
Page 1 of 25
Unit-2
Control Statements
Control Statements are used to control the flow of execution of the program execution. They allow
the program to make decisions, execute specific code blocks, and repeat code sections. Selection
statements( Decision Making Statements), Looping Statements, Jumping statements are types of
control statements.
Selection Statements:
In order to execute or skip a set of instructions based on certain conditions we require the help of
decision making and branching or conditional or selection statements.
1. if statement
2. switch statement
a. Simple-if statement: It contains only the if block which is used to execute set of statements
based on certain condition.
Statements will be executed only when the condition in the expression is true.
Syntax: if(condition)
{
Set of statements
}
The condition expressed may be logical or relational or expression.
E.g.,
if (age >= 18) {
cout << "Adult";
} else {
cout << "Not an adult";
}
Page 2 of 25
Flow Chart:
if
conditi
True
Next statement
Program To Check Whether The Number Is Even Or Odd Using Simple If Statement:
//Program to check the number is even or odd
#include<iostream.h>
void main()
{
int n;
cout<<‖enter the value for n‖;
cin>>n;
if(n%2==0)
{
cout<<―n is even‖;
}
if(n%2!=0)
{
cout<<―n is odd‖;
}
}
b. If-else statement: The if-else statement is a conditional statement which executes the set
of statements in the if block if the condition is true otherwise set of statement within the
else block will be executed. The if-else statement helps in two way decision making.
Syntax: if(condition)
{
Set of statements
}
else
{
Page 3 of 25
Set of statements.
}
c. Nested-if statement: If an if-else statement is placed inside another if-else statement, then
it is called nested-if statement.
Syntax: if(condition)
{
if(condition)
{
Set of statements
}
else
{
Set of statements
}
}
else
{
Set of statements
}
Page 4 of 25
void main()
{
int n;
clrscr();
cout>>‖Enter the value for n‖;
cin>>n;
if(n>=0)
{
if(n==0)
{
cout<<―n is zero‖;
}
else
{
cout<<―n is positive‖;
}
}
else
{
cout<<―n is negative‖;
}
getch();
}
d. Else-if ladder: It is used to select one block out of multiple blocks. It is helpful in multi-
level decision making.
Syntax: if(condition)
{
Set of statements
}
else if(condition)
{
Set of statements
}
else if(condition)
{
Set of statements
}
else
{
Set of statements
}
Page 5 of 25
Program To Display The Total Marks , Grade And Percentage Of Subjects:
#include<iostream.h>
#include<conio.h>
void main()
{
int m1,m2,m3,flag=0,total;
float percentage;
clrscr();
cout<<―enter the marks for m1,m2,m3‖;
cin>>m1>>m2>>m3;
if(m1<35||m2<35||m3<35)
{
flag=1;
}
total=m1+m2+m3;
percentage=float(total)/3;
if(flag==1)
{
cout<<―result=fail‖;
}
else if (percentage >70)
{
cout<<―distinction‖;
}
else if(percentage>60)
{
cout<<―first class‖;
}
else if(percentage>50)
{
cout<<―second class‖;
}
else
{
cout<<―pass class‖;
}
getch();
}
Page 6 of 25
Syntax: switch(expression)
{
case label: statements;
break;
case label: statements;
break;
.
.
.
default :
break;
}
#include<iostream.h>
#include<conio.h>
void main()
{
char ch;
clrscr();
cout<<―enter the character‖;
cin>>ch;
switch(ch)
{
case ‗a‘:
case ‗e‘:
case ‗i‘:
case ‗o‘:
case ‗u‘: cout<<―vowel‖;
break;
default: cout<<―consonant‖;
break;
}
getch();
}
Nested switch statement: If a switch statement is placed inside another switch statement, then
it is called as nested switch statement.
Syntax: switch(expression)
{
case label: switch(expression)
{
case label: statements
break;
Page 7 of 25
.
.
.
default: statements
break;
}
case label: statements;
break;
default: statements;
}
#include<iostream.h>
#include<conio.h>
void main()
{
int dept,desi;
clrscr();
cout<<―enter the value for department 1.sales 2.marketing‖;
cin>>dept;
cout<<―enter the value for designation 1.executive 2.manager‖;
cin>>desi;
switch(dept)
{
case 1: switch(desi)
{
case 1: cout<<―executive in sales‖;
break;
case 2: cout<<―manager in sales‖;
break;
}
break;
case 2: switch(desi)
{
case 1: cout<<―executive in marketing‖;
break;
case 2: cout<<―manager in marketing‖;
break;
}
break;
} getch();
}
Page 8 of 25
Looping/Iteration/Repetition Statements:
Looping statements are also called as iterative statements. It is used to execute a block of
statements repeatedly as long as some conditions are satisfied.
There are three steps in looping statement:
1. Initialization: Used as starting point of iteration.
2. Condition: Used to terminate the iteration.
3. Step: Used to either increment or decrement the initialized variable for repetition.
The variable which is used in all the above steps are called loop control variable.
There are three types of looping statements:
a. While loop.
b. Do-while loop.
c. For loop.
While loop: While loop is an entry controlled loop which executes the block of statements
repeatedly as long as the condition in the expression is true. It is also called as pre-test loop.
Syntax: initialization
while(condition)
{
Block of statements
Increment /decrement the initialized variable
}
STAR
INPUT
INITIALIZATION
CONDI
False
TION
BLOCK OF STATEMENTS
STOP
INCREMENT/DECREMEN
Page 9 of 25
Program to Generate First N Natural Numbers:
//Multiplication table
#include<iostream.h>
#include<conio.h>
void main()
{
int n,i,ans;
clrscr();
cout<<―enter the value for n‖;
cin>>n;
i=1;
while(i<=10)
{
ans=n*i;
cout<<n<<‖x‖<<i<<‖=‖<<ans<<endl;
i++;
}
getch();
}
Do-while loop: The do-while is called as exit controlled statement. The statement block
will execute as long as the condition holds good or true. Entry to the do-while statement
before the testing of condition makes the block of statements to execute at least once. It is
called the post-test loop.
Page 10 of 25
Syntax: Initialization of control variable
do
{
//statement block
[increment/decrement of control variable]
} while(condition);
STAR
INPUT
INITIALIZATION
STATEMENT BLOCK
NEXT STATEMENT
STOP
Page 11 of 25
Program To Simulate The Operations of Simple calculator:
#include<iostream.h>
#include<conio.h>
void main()
{
float n1,n2,res;
int choice;
char ch=‘y‘;
clrscr();
do
{
cout<<―1-Add 2-Sub 3-Mul 4-div‖<<endl;
fflush(stdin);
cin>>choice;
cout<<―enter 2 numbers‖;
cin>>n1>>n2;
switch(choice)
{
case 1: res=n1+n2;
cout<<―sum=‖<<res;
break;
case 2: res=n1-n2;
cout<<―diff=‖<<res;
break;
case 3: res=n1*n2;
cout<<―product=‖<<res;
break;
case 4: res=n1/n2;
cout<<―division=‖<<res;
break;
default: cout<<―invalid choice‖;
}
cout<<―do you wish to continue Y/N‖;
cin>>ch;
} while(ch==‘Y‘)
getch();
}
Page 12 of 25
Difference Between While And Do-While Loop:
for loop: The for loop works in the same manner as the while loop except the initialization
condition and increment/decrement are all part of the syntax. That is, it is an iterative
statement which takes care of the initialization, condition and increment/decrement.
#include<iostream.h>
#include<conio.h>
void main()
{
int n,i,ans;
clrscr();
cout<<―enter the value for n‖;
cin>>n;
Page 13 of 25
for(i=1;i<=10;i++)
{
ans=n*i;
cout<<n<<‖x‖<<i<<‖=‖<<ans<<endl;
}
getch();
}
NESTING OF LOOPS: Cascading of loops is called nesting of loops. That is one loop is
placed inside the body of another loop.
Example: for (initialization ; condition ; increment/decrement)
{
while(condition)
{
Set of statements
}
}
Working of nested loops: Always the inner loop will finish all the iterations and then the
outer loop will go for next iteration.
#include<iostream.h>
#include<conio.h>
void main()
{
int n,m,i,p,j;
clrscr();
cout<<―enter the values for m and n‖;
cin>>m>>n;
for(i=m;i<=n;i++)
{
for(j=1;j<=10;j++)
{
p=j*i;
cout<<j<<‖x‖<<i<<‖=‖<<p<<endl;
}
}
getch();
}
Page 14 of 25
{
for(j=1;j<=5;j++)
{
cout<<―*‖;
}
cout<<endl;
}
1. Break: The break statement is used to come out of the loop that is stop the iteration. It is
also used in switch statement to exit from the block.
Syntax: break;
Example: for(i=1;i<=10;i++)
{
if(i==5)
{
break;
}
cout<<i;
}
Output: 1
2
3
4
2. Continue: Continue statement is used to skip the current iteration and continue with the
next iteration. All the iterations will be executed in the continue statement if we use
Page 15 of 25
continue statement, where as if we use break statement the loop will not execute all the
iterations.
Syntax: continue;
Example: for(i=1;i<=10;i++)
{
if(i==5)
{
continue;
}
cout<<i ;
}
Output: 1
2
3
4
6
7
8
9
10
3. Exit: Exit statement is used to terminate the current program. All the storage area will be
cleared.
Syntax: exit(0);
Example: void main()
{
statements
exit(0);
}
exit(0) Stops executing the program and clears all the associated memory of variables.
exit(0) exit with no errors.
exit(1) exit with some errors.
Page 16 of 25
Modular Programming
Functions:
A function is a set of statements that perform a particular task. Functions helps us to achieve
moo Every C++-program contains at least one function, which is the main() function.
Types of functions:
1. Built-in functions.
2. User-defined functions.
1. Built-in functions: These are the functions which comes along with the C++ compiler
which can be used by specifying the associated header file in the program.
Example:
strcst(),strstr(),strcmp(),gets(),puts() are present in string.h header files.
Sqrt(), sin(), pow(), etc., are present in math.h header files.
2. User-defined functions: These are the functions that are created by the developers for
solving a particular task.
Example: sorting(), searching(), factorial() etc
Functions are also called as methods, sub-programs, sub-routine, procedure, sub-
procedure.
Advantages of functions:
Functions avoid repetition of codes that is; functions written once can be used again and
again.
It increases problem readability.
Through structured programming approach or modular programming approach or top
down design we can break down a complex problem into smaller functions.
Modifying of a program becomes easier by using functions.
Saves lines of codes.
STEP1: Write the function prototype in the global declaration section, that is giving
information to compiler about the function name, arguments and return value.
STEP2: Define the function that is writing the instructions of the functions to do a
particular task. Declare the datatype of return value and declare the function arguments.
STEP3: Use the function by calling its name and passing argument if any.
Note: Arguments/parameters are values which are supplied to the function. Return value
is the value returned by the function.
return(f);
}
Working:
Firstly compiler will call main function.
When control comes inside the main function, statements will be executed in sequence.
Here in the above example we have called a function fact by passing a argument num.
Now control goes to the fact function and executes the statements and returns the computed
factorial value ie., f.
Function will return value f to the calling function(main). It will start executing from the
same place it was called.
Returned value will be assigned to variable ―res‖ and displayed as output in the next steps.
Main function ends.
Program terminates.
Page 18 of 25
Example:
int largest(intx, inty)
{
if(x>y)
return x;
else
return y;
}
As per the syntax we can return one value, but to return more than one variable we can use
arrays/pointers.
Syntax for calling the function:
function name(arguments);
Example: largest(x,y);
Types of functions: Functions are classified into different types based on arguments and
return type.
#include<iostream.h>
#include<conio.h>
int largest(int, int)
void main()
{
int n1,n2,res;
clrscr();
cout<<―enter two numbers‖;
cin>>n1<<n2;
res=largest(n1,n2);
Page 19 of 25
cout<<―largest=‖<<res;
}
int largest(int n1, int n2)
{
if(n1>n2)
{
return n1;
}
else
{
return n2;
}
}
2. Function with argument and without return value:
It is a type of function that contains argument but does not return value.
Syntax: void function name(argument)
{
body of the function
}
Example: Program To Compute Largest Of Two Functions:
#include<iostream.h>
#include<conio.h>
void largest(int, int);
void main();
{
int n1,n2;
cout<<―enter two numbers‖;
cin>>n1<<n2;
largest(n1, n2);
}
void largest(int n1,int n2)
{
if(n1>n2)
cout<<―largest=‖<<n1;
else
cout<<―largest=‖<<n2;
}
Page 20 of 25
Example: Program To Compute Largest Of Two Numbers:
#include<iostream.h>
#include<conio.h>
int largest();
void main()
{
int res;
res=largest();
cout<<―largest=‖<<res;
}
int largest()
{
int n1, n2;
cout<<―enter two numbers‖;
cin>>n1<<n2;
if(n1>n2)
{
return n1;
}
else
{
return n2;
}
}
#include<iostream.h>
#include<conio.h>
void largest();
void main()
{
largest();
}
void largest()
{
int n1,n2;
cout<<―enter two numbers‖;
cin>>n1<<n2;
Page 21 of 25
if(n1>n2)
{
cout<<―largest=‖<<n1;
}
else
{
cout<<―largest=‖<<n2;
}
}
Recursion:
When a function calls itself from its body it is called as recursion.
Syntax: datatype function_name(argument)
{
function_name(argument);
}
#include<iostream.h>
#include<conio.h>
void main()
{
intn,f=0;
clrscr();
cout<<―enter the number‖;
cin>>n;
f=fact(n);
cout<<―factorial=‖<<f;
getch();
}
int fact(int n)
{
if(n==0)
{
return 1;
}
else
{
return(n*fact(n-1));
}
}
Page 22 of 25
Advantages of recursion:
Reduces complexity of the problem.
Through recursion one can solve problems in an easy way.
Disadvantages of recursion:
Recursive solution is always logical and it is very difficult to trace.
Recursion consumes a lot of stack spaces(memory).
Recursion uses more processor time.
Note: Once a parameter is assigned a default value, all parameters to its right must also
have default values.
Inline Functions
Definition: An inline function is a function where the compiler attempts to expand
the function code at the point of each call, rather than invoking the function in the
standard way. i.e. the function code itself is made available at the function call and
no transfer to the function takes place like the way in standard functions.
Purpose: Useful for small, frequently used functions as it can help reduce function
call overhead and improve performance.
Syntax: Declared using the inline keyword before the function.
return a + b;
}
Note: Inline is a request, not a command; the compiler may ignore it if the function is too
complex or recursive.
Page 23 of 25
Function Overloading
Definition: Function overloading allows the same function name to be used for
different functions that differ in their parameter lists (number or type of
parameters). It is a form of polymorphism.
Purpose: Enables functions with the same name but different types or numbers of
arguments, improving readability and code reusability.
Example:
Note: The return type alone is not enough to distinguish overloaded functions.
Page 24 of 25
2. Call by reference: A reference (alias) to the actual argument is passed, so changes
made to the parameter affect the original argument.
#include <cmath>
double result = sqrt(25); // result is 5.0
Page 25 of 25
VISION OF THE INSTITUTE
Empower the individuals and society at large through educational excellence; sensitize them for
a life dedicated to the service of fellow human beings and mother land.
To impact holistic education that enables the students to become socially responsive and useful,
with roots firm on traditional and cultural values; and to hone their skills to accept challenges
and respond to opportunities in a global scenario.
BT
CO’s DESCRIPTION OF THE OUTCOMES
LEVEL
Understand the fundamental concepts and benefits of Object-Oriented
1 Programming (OOP) and how it differs from Procedure-Oriented L2
Programming paradigms.
Interpret and apply C++ syntax and structure, including input-output
statements, keywords, identifiers, constants, variables, data types,
2 L3
operators, expressions and file handling to create basic programs and
solve problems
Describe the control structures, functions, and different parameter
3 L3
passing methods and write programs to solve problems.
Demonstrate the concepts of classes and objects , access specifiers,
4 constructors, destructors, and OOP features like polymorphism, L3
inheritance with the help of programs.
Page 1 of 23
Unit-3
Derived Data Types: Arrays, Array Types, Strings, String Manipulation Functions,
Pointers, Pointer Arithmetic.
Managing Console, I/O Operations: C++ Stream, C++ Stream Classes, Unformatted I/O
Operations, Formatted Console I/O Operations, Managing Output with Manipulators.
User Defined Data Type: Class Definition, Instance Variables, Member Methods,
Accessing Members, Access specifiers, this pointer, Friend Function, Constructors, Types
of Constructors, Destructor.
Arrays
Memory representation:
0 1 2 3 4
Note: Array indices start from 0, so numbers[0] refers to the first element.
Array Types
Page 2 of 23
Memory representation:
0 1 2
0 0,0 0,1 0,2
Examples:
#include<iostream.h>
#include<conio.h>
void main()
{
int a[100],n,i,sum=0;
clrscr();
cout<<enter the number of elements you want to insert:‖;
cin>>n;
for(i=0;i<n;i++)
{
cout<<―enter the element %d:‖<<i+1<<endl;
cin>>a[i])
sum=sum+a[i];
}
cout<<‖the sum of an array is:‖<<sum;
cout<<‖ the average of an array is:‖<<float (sum)\n;
getch();
}
Program To Compute The Sum Of Upper and Lower Diagonal Elements Of A Matrix:
#include<iostream.h>
#include<conio.h>
void main()
{
int a[100][100],n,i,j,sumlower,sumupper;
clrscr();
cout<<―enter the size of an array‖;
cin>>n;
cout<<―enter %d elements of the matrix‖;
for(i=0;i<n;i++)
Page 3 of 23
{
for(j=0;j<n;j++)
{
cin>>a[i][j];
}
}
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
if(i<j)
{
sumupper=sumupper+a[i][j];
}
if(i>j)
{
sumlower=sumlower+a[i][j];
}
}
cout<<―sum of lower diagonal elements=‖<<sumlower;
cout<<‖sum of upper diagonal elements=‖<<sumupper;
getch();
}
Strings
Definition: Strings are sequences of characters. In C++, strings can be handled as character
arrays or as objects of the std::string class.
Character Array Syntax: char str[] = "Hello";
String Class Syntax: std::string str = "Hello";
The compare() function compares two given strings and returns the following
results based on the matching cases:
Page 4 of 23
If both the strings are the same, the function returns 0.
If the character value of the first string is smaller than the second string,
the function returns < 0.
If the second string is greater than the first string, the function returns
greater than 0 or >0.
Examples:
#include <iostream>
#include <string>
using namespace std;
int main () {
string txt = "MIT FGC";
cout <<"Char at(1) ="<< txt.at(1) <<endl;
cout<< "Lenght of string="<<txt.length()<<endl;
cout<<"Sub String ="<<txt.substr(4,6)<<endl;
cout<<"Find position="<<txt.find("F")<<endl;
string s1="MIT", s2="MIT";
cout<<"Compare="<<s1.compare(s2);
return 0;
}
Array of strings
// Driver code
int main()
{
// Initialize String Array
string colour[4] = { "Blue", "Red", "Orange", "Yellow" };
// Print Strings
for (int i = 0; i < 4; i++)
cout << colour[i] << "\n";
return 0;
}
Page 5 of 23
Pointers
Definition: A pointer is a variable that stores the memory address of another variable.
Syntax: data_type* pointer_name;
Example:
Note: * is used to declare a pointer, while & is used to get the address of a variable.
Pointer Arithmetic
Definition: Allows performing arithmetic operations on pointers (like +, -). There are four
arithmetic operators that can be used on pointers: ++, --, +, and -. However, as we know
that pointer contains the address, the result of an arithmetic operation performed on the
pointer will also be a pointer
Example:
Note: When adding or subtracting from a pointer, it moves by the size of the data type.
Increment (++):
To understand pointer arithmetic, let us consider that ptr is an integer pointer which points
to the address 1000 (Assuming 32-bit integers).
Example:
ptr++;
After the above operation, the ptr will point to the location 1004 because each time ptr is
incremented, it will point to the next integer location which is 4 bytes next to the current
location. This operation will move the pointer to the next memory location without
impacting the actual value at the memory location.
The following program increments the variable pointer to access each succeeding element
of the array:
#include <iostream.h>
int main () {
return 0;
}
Output:
Address of var[0] = bf882b30
Value of var[0] = 10
Address of var[1] = bf882b34
Value of var[1] = 100
Address of var[2] = bf882b38
Value of var[2] = 200
Decrement (--): Similar to increment. In this case it will decrease the value by number of
bytes.
Addition (+): We can add a value to the pointer variable. The formula of adding value to
pointer is given below: Adding any number to a pointer will give an address.
new_address= current_address + (number * size_of(data type))
For 64-bit int variable, it will add 4 * number.
#include<iostream.h>
int main()
{
int number=50;
int *p;//pointer to int
p=&number;//stores the address of number variable
cout<<"Address of p variable is‖<<p;
p=p+3; //adding 3 to pointer variable
cout<<"After adding 3: Address of p variable is‖<<p;
return 0;
}
Output:
Address of p variable is 3214864300
After adding 3: Address of p variable is 3214864312
Page 7 of 23
Subtraction (-): Similar to addition.
C++ Stream
Definition: Streams in C++ are used to perform input and output operations. cin is the
standard input stream, and cout is the standard output stream.
Syntax:
C++ Stream Classes: Stream classes in C++ are used to input and output operations on files and
io devices. These classes have specific features and to handle input and output of the program.
The iostream.h library holds all the stream classes in the C++ programming language.
Classes:
o istream: For input operations.
o ostream: For output operations.
o ifstream: For file input. Used for
reading data from files and contains open()
method with default input mode. Inherits the get(), getline(), read() functions from
istream.
o ofstream: For file output.Used for writing data to files. Inherits put(), write()
function from ostream
Usage: These classes provide functionalities to handle different I/O operations.
Page 8 of 23
Stream Class Hierarchy:
Definition: I/O operations that do not involve formatting, such as get(), put(),
getline().
Example: get()
#include<iostream>
using namespace std;
int main()
{
char c=cin.get();
cout<<c<<endl;
return 0;
}
Example: put(): void put() It is a method of cout object and it is used to print the
specified character on the screen or monitor.
#include<iostream>
using namespace std;
int main()
Page 9 of 23
{
char c=cin.get();
cout.put(c);
//Here it prints the value of variable c; cout.put('c'); //Here it prints the character
'c'; return 0;
Definition: I/O operations with specified formatting, using << and >> operators, along with
manipulators. In formatted console input output operations we use built-in functions to
make I/O in perfect alignment.
The ios class contains several member functions that are used to perform formmated IO
operations.
The ios class also contains few format flags used to format the output. It has format flags
like showpos, showbase, oct, hex, etc. The format flags are used by the function setf( ).
The following table provides the details of the functions of ios class used to perform formatted
IO in C++.
Function Description
width(int) Used to set the width in number of character spaces for the immediate output
data.
fill(char) Used to fill the blank spaces in output with given character.
precision(int) Used to set the number of the decimal point to a float value.
setf(format flags) Used to set various flags for formatting output like showbase, showpos, oct,
hex, etc.
unsetf(format Used to clear the format flag setting.
flags)
All the above functions are called using the built-in object cout.
Lets look at the following code to illustrate the formatted IO operations using member functions
of ios class.
Page 10 of 23
Example - Code to illustrate the formatted IO using ios class
#include <iostream>
#include <fstream>
int main()
{
cout << "Example for formatted IO" << endl;
cout.precision(5);
cout << "precision(5) ---> " << 123.4567890 << endl;
cout << "precision(5) ---> " << 9.876543210 << endl;
return 0;
}
Page 11 of 23
Managing Output with Manipulators
Definition: Manipulators are used to format output (e.g., std::setw, std::setprecision, fill,
prescision).
The iomanip.h header file contains several special functions that are used to perform
formmated IO operations.
The following table provides the details of the special manipulator functions used to
perform formatted IO in C++.
Function Description
setw(int) Used to set the width in number of characters for the immediate output
data.
setfill(char) Used to fill the blank spaces in output with given character.
setprecision(int) Used to set the number of digits of precision.
setbase(int) Used to set the number base.
setiosflags(format flags) Used to set the format flag.
resetiosflags(format Used to clear the format flag.
flags)
#include <iostream>
#include <fstream>
Page 12 of 23
void line() {
cout << " " << endl;
}
int main()
{
cout << "Example for formatted IO" << endl;
line();
cout << "setw(10): " << endl;
cout << setw(10) << 99 << endl;
line();
cout << "setw(10) and setfill('*'): " << endl;
cout << setw(10) << setfill('*') << 99 << endl;
line();
cout << "setprecision(5): " << endl;
cout << setprecision(5) << 123.4567890 << endl;
line();
cout << "showpos: " << endl;
cout << showpos << 999 << endl;
line();
cout << "hex: " << endl;
cout << hex << 100 << endl;
line();
cout << "hex and showbase: " << endl;
cout << showbase << hex << 100 << endl;
line();
return 0;
}
Page 13 of 23
User Defined Data Type
A UDT allows users to define their own data types. For example, in a library
management system, we can create a UDT called 'Book' to store information about
books like title, author, genre, etc.
Example:
class Book
{
string title;
string author;
string genre;
public:
void issue();
void return();
void getdata();
Page 14 of 23
};
Class Definition
Definition: A class is a blueprint for creating objects, encapsulating data and methods.
Syntax:
class ClassName
{
Access Specifier: //public, protected, private
//properties and methods are declared here
};
Example:
// Class definition
class Book {
private:
string title;
string author;
public:
Book() {}
void setTitle(string newTitle) { title = newTitle; }
void setAuthor(string newAuthor) { author = newAuthor;}
string getTitle() const { return title; }
string getAuthor() const { return author; }
};
Creating objects & Accessing class members
Syntax:
Class_name obj_name;
Ex:
STUDENT sObj;
Syntax to access data members:
object_name.data_member;
object_name.function_name(arguments);
Ex:
sObj.accept();
Instance Variables
Definition: Instance variables are the variables defined within a class, representing the
properties of each object created from the class
Example: In the Car class example, brand and year are instance variables.
Car myCar;
myCar.brand = "Toyota";
myCar.year = 2020;
Here, myCar is an instance of the Car class, and brand and year are instance variables for that
instance.
Member Methods
void display()
{
std::cout << "Displaying information";
}
Page 16 of 23
Member functions can be defined in two ways
1. Inside the class- when a function is defined inside a class it is treated as INLINE
function.
2. Outside the class (using scope resolution operator ::)
Syntax to define functions outside the class:
Accessing Members
Person p;
p.age = 25;
p.display();
Access Specifiers
Access specifiers define the visibility of class members. There are three types:
Types:
o public: Accessible from outside the class.
o private: Accessible only within the class.
o protected: Accessible within the class and derived classes.
Example:
class Car
{
public:
string brand;
private:
int year;
};
Page 17 of 23
In this example, brand is accessible outside the class, but year is private and can‘t be accessed
directly.
this Pointer
this->data = data;
Example:
class Car {
public:
string brand;
int year;
Car(string brand, int year) {
this->brand = brand;
this->year = year;
}
};
In this example, this->brand refers to the instance variable brand, while brand refers to the
parameter.
Friend Function
Definition: A function not a member of the class but has access to its private and protected
members. It is defined outside the class. But the function prototype must be inside the class
declaration to make it a friend function.
Syntax:
Page 18 of 23
Constructors
Definition: Special member functions used to initialize objects. It is called when the
object is created.
Example:
class Car {
public:
string brand;
int year;
Car() {
brand = "Unknown";
year = 0;
}
};
Here, Car() is a default constructor that initializes brand and year when an object is created.
Types:
o Default Constructor: Takes no parameters.
o Parameterized Constructor: Takes parameters to initialize attributes.
o Copy Constructor: Initializes an object using another object of the same class.
Syntax:
class MyClass {
public:
MyClass() { } // Default
MyClass(int a) { } // Parameterized
MyClass(const MyClass &obj) { } // Copy
};
Examples:
1. Default Constructor:
Car() {
brand = "Unknown";
year = 0;
}
2. Parameterized Constructor:
Car(string b, int y) {
brand = b;
year = y;
}
3. Copy Constructor:
Car(const Car &obj) {
brand = obj.brand;
Page 19 of 23
year = obj.year;
}
2. No Return Type
3. Automatically Invoked
4. Can Be Overloaded
You can have multiple constructors in a class with different parameter lists. This is
known as constructor overloading.
The correct constructor is chosen based on the arguments provided when the object is
created.
Example:
class Car {
public:
Car() { } // Default constructor
Car(string b, int y) { } // Parameterized
Destructor
Definition: Special member function with the same name as the class, preceded by ~
(tilde operator). It is used to release resources allocated to the object. It takes no
arguments.
Syntax:
~MyClass() { }
Page 20 of 23
Example
class Car {
public:
Car() {
cout << "Car created" << endl;
}
~Car() {
cout << "Car destroyed" << endl;
}
};
In this example, the destructor ~Car() will be called automatically when the Car object goes out
of scope.
Page 21 of 23
Full program example for the above mentioned concepts:
#include <iostream>
using namespace std;
class Car {
public:
string brand;
int year;
void displayInfo() {
cout << "Brand: " << brand << ", Year: " << year << endl;
}
~Car() { // Destructor
cout << "Car destroyed" << endl;
}
};
int main() {
Car car1("Toyota", 2015); // Creating object using parameterized constructor
car1.displayInfo();
return 0;
}
Output:
Brand: Toyota, Year: 2015
Brand: Toyota, Year: 2015
Page 22 of 23
Car destroyed
Car destroyed
In this example:
The Car class has a parameterized constructor, a copy constructor, and a destructor.
We create car1 with the parameterized constructor and car2 with the copy constructor.
When the program ends, the destructor is called twice, once for each object.
Page 23 of 23
VISION OF THE INSTITUTE
Empower the individuals and society at large through educational excellence; sensitize them for
a life dedicated to the service of fellow human beings and mother land.
To impact holistic education that enables the students to become socially responsive and useful,
with roots firm on traditional and cultural values; and to hone their skills to accept challenges
and respond to opportunities in a global scenario.
BT
CO’s DESCRIPTION OF THE OUTCOMES
LEVEL
Understand the fundamental concepts and benefits of Object-Oriented
1 Programming (OOP) and how it differs from Procedure-Oriented L2
Programming paradigms.
Interpret and apply C++ syntax and structure, including input-output
statements, keywords, identifiers, constants, variables, data types,
2 L3
operators, expressions and file handling to create basic programs and
solve problems
Describe the control structures, functions, and different parameter
3 L3
passing methods and write programs to solve problems.
Demonstrate the concepts of classes and objects , access specifiers,
4 constructors, destructors, and OOP features like polymorphism, L3
inheritance with the help of programs.
Page 1 of 19
Unit 4
Unit-4
Polymorphism: Operator Overloading, Rules for Operator Overloading, 11
Overloading Unary and Binary Operators. Hours
Inheritance: Inheritance, Types of Inheritance, Virtual Functions and Abstract
Classes.
File Handling: Introduction To Files and File Handling, File Opening Modes, Classes
For File Stream Operations, File I/O Operations (Opening, Reading, Writing,
Append And Closing).
Polymorphism in C++
Polymorphism is the ability of a function, object, or operator to take on multiple forms. It allows
for a more flexible and reusable code.
Function Overloading: Defining multiple functions with the same name but different
parameters (either in number or type). The compiler determines which function to call
based on the arguments provided at compile time.
Operator Overloading: Defining operators (like +, -, <<, >>) to work with user-defined
types.
Operator Overloading
Operator overloading is a type of polymorphism where operators are given a new meaning when
applied to user-defined types (like classes). By overloading an operator, you define how it behaves
for objects of your class.
Page 2 of 19
� To overload an operator, we use a special function called an operator function.
Here op_symbol is used as the symbol for the operator being overloaded and operator is a keyword.
Create a class that defines the data type that is to be used in the overloading operation.
Declare the operator function in the public part (it can be a friend function too)
Define the operator function to implement the required operation.
1. Only Existing Operators Can Be Overloaded: You cannot create new operators.
2. Cannot Change Operator Precedence or Associativity: Overloading doesn‘t affect the
precedence of operators.
3. Cannot Overload Certain Operators:
Sizeof operator
. Member access operator
.* pointer to member operator
:: scope resolution operator
?: Conditional operator
4. Syntax: The syntax for operator overloading must follow the syntax rules for the operator
being overloaded.
5. At Least One Operand Must Be a User-Defined Type: You can‘t change the behavior
of operators for built-in types.
6. Unary operators typically do not take parameters when overloaded.
7. Binary operators typically take one parameter for overloading. But those overloaded
using friend function takes one two argument
class Complex {
private:
double real;
double imag;
Page 3 of 19
public:
Complex(double r = 0, double i = 0) : real(r), imag(i) {}
int main() {
Complex c1(2, 3);
Complex c2 = -c1; // Using the overloaded unary negation operator
c1.display(); // Output: 2 + 3i
c2.display(); // Output: -2 - 3i
return 0;
}
#include <iostream>
using namespace std;
class Complex
{
private:
float real, imag;
public:
Complex(float r = 0, float i = 0)
{
real=r;
imag=i;
Page 4 of 19
}
int main()
{
Complex c1(2, 3), c2(1.5, 2.5);
Complex c3 = c1 + c2; // Using overloaded + operator
c3.display(); // Output: 4 + 6i
return 0;
}
Output:
3.5 + 5.5i
Inheritance in C++
Inheritance allows one class (derived class) to acquire properties and behavior from another class
(base class). It supports code reuse and polymorphism. It allows us to create a new class (derived
class) from an existing class (base class). The derived class inherits the features from the base class
and can have additional features of its own. Inheritance is an is-a relationship. We use inheritance
only if an is-a relationship is present between the two classes. Here are some examples: A car is a
vehicle, Orange is a fruit.
Types of Inheritance
1. Single Inheritance: A derived class inherits from a single base class.
2. Multiple Inheritance: A derived class inherits from more than one base class.
3. Multilevel Inheritance: A class is derived from a class which is also derived from
another class.
4. Hierarchical Inheritance: Multiple classes inherit from a single base class.
5. Hybrid Inheritance: Combination of two or more types of inheritance.
Page 5 of 19
The Syntax of Derived class:
class derived_class_name : visibility-mode base_class_name
{
// body of the derived class.
}
Example:
class Base {
.... ... ....
};
Page 6 of 19
Example for Single Inheritance:
#include <iostream>
using namespace std;
// Base class
class Windows10 {
public:
void boot() {
cout << "Booting Windows 10..." << endl;
}
};
// Derived class
class Windows11 : public Windows10 {
public:
void newFeature() {
cout << "Welcome to Windows 11 with new features!" << endl;
}
};
int main() {
Windows11 myWindows11;
return 0;
}
Output:
Booting Windows 10...
Welcome to Windows 11 with new features!
This example illustrates single inheritance where Windows11 inherits functionality from
Windows10, showcasing how derived classes can build upon the base class functionality.
Page 7 of 19
Example for Multilevel Inheritance:
#include <iostream>
using namespace std;
// Base class
class Windows10 {
public:
void boot() {
cout << "Booting Windows 10..." << endl;
}
};
int main() {
Windows12 myWindows12;
return 0;
}
Output:
Booting Windows 10...
Page 8 of 19
Welcome to Windows 11 with new features!
Enjoying the latest features in Windows 12!
// Base class 1
class Windows {
public:
void bootWindows() {
cout << "Booting Windows environment." << endl;
}
};
// Base class 2
class Linux {
public:
void bootLinux() {
cout << "Booting Linux environment." << endl;
}
};
int main() {
NewOS myOS;
// Using methods from both base classes and the derived class
myOS.bootWindows(); // Inherited from Windows
Page 9 of 19
myOS.bootLinux(); // Inherited from Linux
myOS.bootNewOS(); // Defined in NewOS
return 0;
}
Output:
Booting Windows environment.
Booting Linux environment.
Booting NewOS with features of both Windows and Linux.
This example demonstrates multiple inheritance in C++, where the NewOS class inherits
features from both Windows and Linux classes.
// Base class
class Windows {
public:
void boot() {
cout << "Booting Windows..." << endl;
}
};
Page 10 of 19
// Derived class for Windows 10
class Windows10 : public Windows {
public:
void displayVersion() {
cout << "This is Windows 10." << endl;
}
};
int main() {
Windows7 win7;
Windows8 win8;
Windows10 win10;
return 0;
}
Output:
For Windows 7:
Booting Windows...
This is Windows 7.
For Windows 8:
Booting Windows...
This is Windows 8.
Page 11 of 19
This is Windows 10.
// Base class
class OperatingSystem {
public:
void boot() {
cout << "Booting Operating System..." << endl;
}
};
Page 12 of 19
}
};
int main() {
NewOS myOS;
return 0;
}
Output:
Booting Operating System...
This is a Windows operating system.
This is a Linux operating system.
This is NewOS with features from Windows and Linux.
This example illustrates hybrid inheritance where the NewOS class derives features from both
Windows and Linux, which in turn derive from a common base class OperatingSystem. This
structure allows NewOS to combine functionalities from multiple sources effectively.
public inheritance makes public members of the base class public in the derived class, and
the protected members of the base class remain protected in the derived class.
protected inheritance makes the public and protected members of the base
class protected in the derived class.
private inheritance makes the public and protected members of the base class private in the
derived class.
Note: private members of the base class are inaccessible to the derived class.
Page 13 of 19
Scope/Accessing Members during Inheritance:
Exmaple:
class Base {
public:
int x;
protected:
int y;
private:
int z;
};
Page 14 of 19
class PrivateDerived: private Base {
// x is private
// y is private
// z is not accessible from PrivateDerived
};
Virtual Functions
Virtual Functions: Used in a base class to allow derived classes to override it. Virtual
functions enable runtime polymorphism.
Pure Virtual Functions: A pure virtual function is a virtual function that has no definition
within the class. A pure virtual function is a "do nothing"/empty function. Here "do
nothing" means that it just provides the template, and derived class implements the
function. A class having pure virtual function cannot be used to create direct objects of its
own. Example: virtual void f() = 0;
Example for Virtual function to show the dynamic binding(run time polymorphism):
#include <iostream>
using namespace std;
class Base {
public:
virtual void print() {
cout << "Base Function" << endl;
}
};
int main() {
Derived derived1;
Page 15 of 19
// calls member function of Derived class
base1->print();
return 0;
}
Output:
Derived Function
Abstract Classes
A class with at least one pure virtual function (i.e., virtual void func() = 0;). Objects cannoted be
created for abstract class and serves only as a base class.
Example:
class Shape {
public:
};
Page 16 of 19
File Handling in C++
File handling involves storing and retrieving data to and from files using file streams. C++ provides
classes and functions for handling file I/O.
In C++, file stream operations are primarily handled through the standard library, specifically using
the <fstream> header. This header provides several classes that allow you to work with files in a
convenient and efficient way. Here‘s an overview of the main classes for file stream operations:
1. fstream
Description: The fstream class is used for both input and output file operations. It allows
you to read from and write to a file using the same object.
Usage: It is suitable for cases where you want to read from and write to the same file.
Example:
or
fstream myfile;
myfile.open("example.txt", ios::in | ios::out | ios::app);
2. ifstream
Description: The ifstream class is used specifically for input file operations. It allows you
to read data from a file.
Usage: It is ideal for cases where you only need to read data from a file.
Page 17 of 19
3. ofstream
Description: The ofstream class is used specifically for output file operations. It allows
you to write data to a file.
Usage: It is ideal for cases where you only need to write data to a file.
1. Opening a File
ofstream outfile;
outfile.open("example.txt", ios::out);
2. Writing to a File
if (outfile.is_open()) {
outfile << "Hello, World!" << endl;
outfile.close();
}
3. Reading from a File
ifstream infile("example.txt");
string line;
if (infile.is_open()) {
while (getline(infile, line)) {
cout << line << endl;
}
infile.close();
}
4. Appending to a File
ofstream outfile("example.txt", ios::app);
if (outfile.is_open()) {
outfile << "Appending this text." << endl;
outfile.close();
}
5. Closing a File: Always close files after performing file operations to avoid resource leaks.
inFile.close();
Page 18 of 19
Example for reading and writing operations on file:
#include <iostream>
#include <fstream>
using namespace std;
int main() {
// Write to file
ofstream outFile("sample.txt");
if (outFile.is_open()) {
outFile << "Writing to file." << endl;
outFile.close();
}
return 0;
}
Note:This program opens a file named sample.txt, writes a line to it, closes the file, then
reopens it to read and print the contents.
Page 19 of 19