Oops Notes Final
Oops Notes Final
Unit – 1
Comparison of Procedural and Object Oriented Programming
Procedural Programming
Object-Oriented Programming
Class:
The building block of C++ that leads to Object-Oriented programming is a Class.
It is a user-defined data type, which holds its own data members and member
functions, which can be accessed and used by creating an instance of that class. A
class is like a blueprint for an object.
● A Class is a user-defined data-type which has data members and member
functions.
● Data members are the data variables and member functions are the
functions used to manipulate these variables and together these data
members and member functions define the properties and behaviour of the
objects in a Class.
● In the above example of class Car, the data member will be speed limit,
mileage etc and member functions can apply brakes, increase speed etc.
We can say that a Class in C++ is a blue-print representing a group of objects
which shares some common properties and behaviors.
Object:
An Object is an identifiable entity with some characteristics and behaviour.
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.
classperson
{
charname[20];
intid;
public:
voidgetdetails(){}
};
intmain()
{
person p1; // p1 is a object
}
Object take up space in memory and have an associated address like a record in
pascal or structure or union in C.
When a program is executed the objects interact by sending messages to one
another.
Each object contains data and code to manipulate the data. Objects can interact
without having to know details of each other’s data or code, it is sufficient to
know the type of message accepted and type of response returned by the objects.
Encapsulation:
In normal terms, Encapsulation is defined as wrapping up of data and
information under a single unit. In Object-Oriented Programming, Encapsulation
is defined as binding together the data and the functions that manipulate them.
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.
A person at the same time can have different characteristic. Like a man at the
same time is a father, a husband, an employee. So the same person posses
different behaviour in different situations. This is called polymorphism.
Inheritance:
The capability of a class to derive properties and characteristics from another
class is called Inheritance. Inheritance is one of the most important features 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.
● Reusability: Inheritance supports the concept of “reusability”, i.e. when we
want to create a new class and there is already a class that includes some of
the code that we want, we can derive our new class from the existing class.
By doing this, we are reusing the fields and methods of the existing class.
Example: Dog, Cat, Cow can be Derived Class of Animal Base Class.
Dynamic Binding:
In dynamic binding, the code to be executed in response to function call is
decided at runtime. C++ has virtual functions to support this.
Message Passing:
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.
Datatypes in C++
1. Primary(Built-in) Data Types:
character
integer
floating point
boolean
double floating point
void
wide character
Structure
Union
Class
Enumeration
The data types that are defined by the user are called the derived datatype
or user-defined derived data type.
Class:
The building block of C++ that leads to Object Oriented
programming is a Class. It is a user defined data type, which holds its own
data members and member functions, which can be accessed and used by
creating an instance of that class. A class is like a blueprint for an object.
Structure:
A structure is a user defined data type in C/C++. A
structure creates a data type that can be used to group items of possibly
different types into a single type.
Syntax
struct address
{
char name[50];
char street[100];
char city[50];
char state[20];
int pin;
};
Union:
Syntax
union address
{
char name[50];
char street[100];
char city[50];
char state[20];
int pin;
};
Enumeration:
Syntax
enum week
{
Mon,
Tue,
Wed,
Thur,
Fri,
Sat,
Sun
};
2.Built in Data Type
Data types in C++ is mainly divided into two types: Primitive Data
Types: These data typesare built-in or predefined data types and can be
used directly by the user to declare variables. example: int, char , float,
bool etc.
:
These data types are built-in or predefined data types and can be
used directly by the user to declare variables. example: int, char , float,
bool etc.
Integer: Keyword used for integer data types is int. Integers typically
requires 4 bytes of memory space and ranges from -2147483648 to
2147483647.
Character: Character data type is used for storing characters.
Keyword used for character data type is char. Characters typically requires
1 byte of memory space and ranges from -128 to 127 or 0 to 255.
Boolean: Boolean data type is used for storing boolean or logical
values. A boolean variable can store either true or false. Keyword used for
boolean data type is bool.
FloatingPoint:Floating Point data type is used for storing single
precision floating point values or decimal values. Keyword used for floating
point data type is float. Float variables typically requires 4 byte of memory
space.
Double Floating Point: Double Floating Point data type is used for
storing double precision floating point values or decimal values. Keyword
used for double floating point data type is double. Double variables
typically requires 8 byte of memory space.
void: Void means without any value. void datatype represents a
valueless entity. Void data type is used for those function which does not
returns a value.
1. Array
2. Function
3. Pointer
Array
An array is simply a collection of variables of the
same data type that are referenced by a common name. In other words,
when elements of linear structures are represented in the memory by
means of contiguous memory locations, these linear structures are called
arrays.
type array_name[array_size];
Example
Int arr[10];
Functions
A function declaration tells the compiler about a function's
name, return type, and parameters. A function definition provides the
actual body of the function. The C++ standard library provides numerous
built-in functions that your program can call.
Function prototype or function interface is a declaration of
a function that specifies the function's name and type signature (arity, data
types of parameters, and return type), but omits the function body.
Syntax
Function name ()
{
--------
--------
}
Pointers
Syntax
Int *a
Variables
A variable is a name of memory location. It is used to store data. Its value can be
changed and it can be reused many times.
It is a way to represent memory location through symbol so that it can be easily
identified.
Syntax
data_type variable_name;
Example
int x;
float y;
char z;
Constant
The const keywords used to define the constant value that cannot change
during program execution. It means once we declare a variable as the constant in
a program, the variable's value will be fixed and never be changed. If we try to
change the value of the const type variable, it shows an error message in the
program.
Const variable
It is a const variable used to define the variable values that never be changed
during the execution of a program. And if we try to modify the value, it throws an
error.
Syntax:
const data_type variable_name;
Example
Const int a= 10;
Example Program
#include <iostream>
#include <conio.h>
using namespace std;
int main ()
{
// declare the value of the const
const int num = 25;
num = num + 10;
return 0;
}
For example, we are adding two numbers, where one variable is of int type
and another of float type; we need to convert or typecast the int variable into a
float to make them both float data types to add them.
Type conversion can be done in two ways in C++, one is implicit type
conversion, and the second is explicit type conversion. Those conversions are
done by the compiler itself, called the implicit type or automatic type conversion.
The conversion, which is done by the user or requires user interferences called
the explicit or user define type conversion. Let's discuss the implicit and explicit
type conversion in C++.
Implicit Type Conversion
The implicit type conversion is the type of conversion done automatically by the
compiler without any human effort. It means an implicit conversion automatically
converts one data type into another type based on some predefined rules of the
C++ compiler. Hence, it is also known as the automatic type conversion.
For example:
int x = 20;
short int y = 5;
int z = x + y;
Conversions that require user intervention to change the data type of one
variable to another, is called the explicit type conversion. In other words, an
explicit conversion allows the programmer to manually changes or typecasts the
data type from one variable to another type. Hence, it is also known as
typecasting. Generally, we force the explicit type conversion to convert data from
one type to another because it does not follow the implicit conversion rule.
Example Program
#include <iostream>
using namespace std;
int main ()
{
float f2 = 6.7;
// use cast operator to convert data from one type to another
int x = static_cast <int> (f2);
cout << " The value of x is: " << x;
return 0;
}
Operators in C++
An operator is a symbol that tells the compiler to perform specific
mathematical or logical manipulations. C++ is rich in built-in operators and
provide the following types of operators −
● Arithmetic Operators
● Relational Operators
● Logical Operators
● Bitwise Operators
● Assignment Operators
Arithmetic Operators
Relational Operators
Logical Operators
Operator Description Example
Bitwise Operators
Operator Description Example Operator Description
& Binary AND Operator (A & B) will give 12 & Binary AND Operator
copies a bit to the which is 0000 1100 copies a bit to the
result if it exists in result if it exists in
both operands. both operands.
Assignment Operators
Operator Description Example
Misc Operators
Sr.No Operator & Description
1 sizeof
sizeof operator returns the size of a variable. For example, sizeof(a), where ‘a’ is
integer, and will return 4.
2 Condition ? X : Y
Conditional operator (?). If Condition is true then it returns value of X otherwise
returns value of Y.
3 ,
Comma operator causes a sequence of operations to be performed. The value of the
entire comma expression is the value of the last expression of the comma-separated
list.
4 . (dot) and -> (arrow)
Member operators are used to reference individual members of classes, structures,
and unions.
5 Cast
Casting operators convert one data type to another. For example, int(2.2000) would
return 2.
6 &
Pointer operator & returns the address of a variable. For example &a; will give actual
address of the variable.
7 *
Pointer operator * is pointer to a variable. For example *var; will pointer to a variable
var.
1.Branching
2.Looping
Branching statement
if statement
if..else statements
if-else-if ladder
nested if statements
switch statements
If Statement:
if-else-if ladder
Looping
A loop statement allows us to execute a statement or group of
statements multiple times and following is the general from of a loop
statement in most of the programming languages
C++ while and do...while Loop. Loops are used in programming to
repeat a specific block of code. ... In computer programming, loop repeats a
certain block of code until some end condition is met.
Types of Loop
1.Entry control Loop
i)For Loop
ii)While Loop
2.Exit Control Loop
i) Do while Loop
for Loop
Syntax
for(initializationStatement;
testExpression;increment/decre
ment)
// codes
}
Example
for(i=0;i<=5;i++)
while Loop
Syntax
while
(testExpression)
{
// codes
}
Example
I=0;
while (i<=5)
{
Cout<<” SRM IST”
i++;
}
Do While Loop
The do...while loop is a variant of the while loop with one important
difference. The body of do...while loop is executed once before the test
expression is checked.
● The codes inside the body of loop is executed at least once. Then, only
the test expression is checked.
● If the test expression is true, the body of loop is executed. This
process continues until the test expression becomes false.
● When the test expression is false, do...while loop is terminated.
Syntax
do
{
// codes;
}
while
(testExpression);
Example
do
{
Cout<<”SRM IST “;
}
while (i<=5);
Example Program
#include <stdio.h>
int main()
{
int sum=0;
for(inti=1;i<=50;i++)
{
sum=sum+i;
}
printf("Sum=%d",sum);
return 0; }
Functions
A function is a group of statements that together perform a task.
Every C++program has at least one function, which is main(), and all the
most trivial programs can define additional functions. ...
A function declaration tells the compiler about afunction's name, return
type, and parameters.
Syntax:
// function-body
● return-type: suggests what the function will return. It can be int, char,
some pointer or even a class object. There can be functions which
does not return anything, they are mentioned with void.
● Function Name: is the name of the function, using the function name
it is called.
● Parameters: are variables to hold values of arguments passed while
function is called. A function may or may not contain parameter list.
● Function body: is the part where the code statements are written.
1. Call by Value
2. Call by Reference
Call by Value
int main()
int x = 10;
calc(x);
printf("%d", x);
void calc(int x)
x = x + 10 ;
Call by Reference
int main()
int x = 10;
printf("%d", x);
*p = *p + 10;
Main Function
Syntax:
Void main
---------
-----------
Default arguments
C++ Recursion
When function is called within the same function, it is known as recursion
in C++. The function which calls the same function, is known as recursive function.
A function that calls itself, and doesn't perform any task after function call,
is known as tail recursion. In tail recursion, we generally call the same function
with return statement.
Syntax:
recursionfunction()
{
recursionfunction(); //calling self function
}
Example
#include<iostream>
using namespace std;
int main()
{
int factorial(int);
int fact,value;
cout<<"Enter any number: ";
cin>>value;
fact=factorial(value);
cout<<"Factorial of a number is: "<<fact<<endl;
return 0;
}
int factorial(int n)
{
if(n<0)
return(-1); /*Wrong value*/
if(n==0)
return(1); /*Terminating condition*/
else
{
return(n*factorial(n-1));
}
}
Inline Function
C++ inline function is powerful concept that is commonly used with classes.
If a function is inline, the compiler places a copy of the code of that function at
each point where the function is called at compile time.
Any change to an inline function could require all clients of the function to
be recompiled because compiler would need to replace all the code once again
otherwise it will continue with old functionality.
To inline a function, place the keyword inline before the function name and
define the function before any calls are made to the function. The compiler can
ignore the inline qualifier in case defined function is more than a line.
A function definition in a class definition is an inline function definition,
even without the use of the inline specifier.
Example Program
#include <iostream>
using namespace std;
inline int Max(int x, int y)
{
return (x > y)? x : y;
}
int main()
{
cout<< "Max (20,10): " << Max(20,10) << endl;
cout<< "Max (0,200): "<< Max(0,200) << endl;
cout<< "Max (100,1010): " << Max(100,1010) << endl;
return 0; }
Class and object
Class
C++ Classes and Objects. Class: The building block of C++ that
leads to Object Oriented programming is a Class. It is a user defined data
type, which holds its own data members and member functions, which
can be accessed and used by creating an instance of that class.
Syntax
Class class_name
Example
Class bca
Syntax
Class_name object-name
Example
Bca aa;
Member function Definition
There are 2 ways to define a member function:
● Inside class definition
● Outside class definition
Inside class
class bca
{
public :
int a,b,c:;
sum() // function definition
{
c=a+b;
}
};
Outside class
class bca
{
public :
int a,b,c:;
sum() // function Declaration
};
void bca :: sum() // function definition
{
c=a+b;
}
To define a member function outside the class definition we have to
use the scope resolution :: operator along with class name and function
name.
Array of object
● Like array of other user-defined data types, an array of type class can also
be created.
● The array of type class contains the objects of the class as its individual
elements.
● Thus, an array of a class type is also known as an array of objects.
● An array of objects is declared in the same way as an array of any built-in
data type.
Syntax
class class-name
datatype var1;
datatype varN;
method1();
method2();
methodN();
};
Example
Class aaa
Void main()
Example program
#include<iostream.h>
#include<conio.h>
#include<stdio.h>
Classemp
{
inteid;
doublehra, pf, da, cca, nf, bp;
charename[10];
public:
void getdata()
{
cout<<”enter name of the employee:”<<endl;
gets(name);
cout<<”enter employee id:”<<endl;
cin>>eid;
cout<<”enter employee basic pay:”<<endl;
cin>>bp;
}
void allow()
{
hra=(bp*10)/100;
pf=(bp*12)/100;
da=(bp*11)/100;
cca=(bp*8)/100;
np=(bp+hra+da+cca)-pf;
}
Void putdata();
{
cout<<”employee name is:”<<ename<<endl;
cout<<”employee id is:”<<eid<<endl;
cout<<”employee basic pay is:”<<bp<<endl;
cout<<”\nhra=”<<hra<<”\n da=”<<da<<”\n pf=”<<pf<<”\n cca=”<<cca;
cout<<”\n net pay of employee is:”<<np<<endl;
}
};
void main()
{
clrscr();
int n;
emp e[100];
cout<<”\n \t Arrays Of Objects”;
cout<<”\n enter number of employees:”<<endl;
cin>>n;
for(inti=0;i<n;i++)
{
cout<<”entering the details of employee:”<<i+1<<endl;
e[i].getdata();
e[i].allow();
}
clrscr();
for(inti=0;i<n;i++)
{
cout<<”displaying details of employee:”<<i+1<<endl;
e[i].putdata();
cout<<endl;
}
getch();
}
UNIT – 2
Constructor and Destructorin C++
● Constructor has same name as the class itself.
● Constructors don't have return type.
● A constructor is automatically called when an object is created.
● If we do not specify a constructor, C++ compiler generates a
default constructor for us (expects no parameters and has an empty body).
Uses
class Name()
{
//set fields and call methods
}
Example
Class bca
{
Bca ()
{
Cout << “Welcome;
}
};
Void main()
{
Bca b; // Constructor will call Automatically
}
Constructor overloading
Constructor overloading in C++ programming is same as
function overloading. When we create more that one constructors in a class with
different number of parameters or different types of parameters or different
order of parameters, it is called as constructor overloading
Example program
#include <iostream>
using namespace std;
class Room
{
private:
double length;
double breadth;
public:
Room()
{
length = 6.9;
breadth = 4.2;
}
Room(double l, double b)
{
length = l;
breadth = b;
}
Room(double len)
{
length = len;
breadth = 7.2;
}
double calculateArea()
{
return length * breadth;
}
};
int main()
{
Room room1, room2(8.2, 6.6), room3(8.2);
cout<< "Area of room = " << room3.calculateArea() << endl;
return 0;
}
Types of Constructor
Default Constructor.
Parameterized Constructor.
Copy Constructor.
Default Constructor.
Default Constructors: Default constructor is the constructor which
doesn't take any argument. It has no parameters. .
Default constructor for a class as a constructor that can be called
with no arguments (this includes a constructor whose parameters all have
default arguments)
Syntax:
constructor_name ( ) ; // Declaration
{
------ // Body of the constructor
}
Example Program
#include <iostream>
using namespace std;
class Employee
{
public:
Employee()
{
cout<<"Constructor Invoked"<<endl;
}
~Employee()
{
cout<<"Destructor Invoked"<<endl;
}
};
int main(void)
{
Employee e1; //creating an object of Employee
Employee e2; //creating an object of Employee
return 0;
}
Parameterized constructor
An object is declared in a parameterized constructor, the initial
values have to be passed as arguments to the constructor function. The
normal way of object declaration may not work. Theconstructors can be
called explicitly or implicitly.
Syntax
{
------ // Body of the constructor
}
Example program
#include <iostream>
using namespace std;
class Employee {
public:
int id;//data member (also instance variable)
string name;//data member(also instance variable)
float salary;
Employee(int i, string n, float s)
{
id = i;
name = n;
salary = s;
}
void display()
{
cout<<id<<" "<<name<<" "<<salary<<endl;
}
};
int main(void) {
Employee e1 =Employee(101, "Sonoo", 890000);
Employee e2=Employee(102, "Nakul", 59000);
e1.display();
e2.display();
return 0;
}
Copy Constructor
Syntax
class class_name{
public:
class_name(class_name & obj)
{
// obj is same class another object
// Copy Constructor code
}
//... other Variables & Functions
}
Example
Main ()
{
class_name object1(params);
Method 1 - Copy Constrcutor
class_name object2(object1);
Method 2 - Copy Constrcutor
class_name object3 = object1;
}
Destructor
Syntax:
Class class_name
{
public:
~class_name() //Destructor
{
}
}:
Example
Class bca
{
public:
~bca() //Destructor
{
}
}:
Types of overloading in C++ are:
o Function overloading
o Operator overloading
Rules
● The same function name is used for more than one function definition
● The functions must differ either by the arity or types of their parameters
Types
● Different number of parameter
● Different types of parameter
● Different parameter with different return values
Class aaa
Int Sum(int a, Int b) // Integer return type
{
}
float Sum(float x, int y) // Float return type
{
}
Example program
#include <iostream>
class Add
{
public:
int sum(int num1,int num2) // Integer return type
{
return num1+num2;
}
float sum(float num3,int num4) // Float return type
{
return num3+num4;
}
};
int main(void)
{
Addition obj;
cout<<obj.sum(20, 15);
cout<<obj.sum(81.50, 100);
return 0;
}
Operator Overloading
The unary operators operate on a single operand and following are the examples
of Unary operators −
●The increment (++) and decrement (--) operators.
● The unary minus (-) operator.
● The logical not (!) operator
Syntax
#include <iostream>
using namespace std;
class Test
{
private:
int num;
public:
Test(): num(8){}
void operator ++()
{
num = num+2;
}
void Print() {
cout<<"The Count is: "<<num;
}
};
int main()
{
Test tt;
++tt; // calling of a function "void operator ++()"
tt.Print();
return 0;
}
Binary Operator Overloading
Syntax
Example Program
#include <iostream>
using namespace std;
class A
{
int x;
public:
A(){}
A(int i)
{
x=i;
}
void operator+(A);
void display();
};
void A :: operator+(A a)
{
int m = x+a.x;
cout<<"The result of the addition of two objects is : "<<m;
}
int main()
{
A a1(5);
A a2(4);
a1+a2;
return 0;
}
UNIT -3
1 -Inheritance
Inheritance is the process of creating new classes, called derived classes,
from existing classes or base classes. The derived class inherits all the
capabilities of the base class.An inherited class is called a subclass of its parent
class or super class.
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.
Syntax
!.Single Inheritance
2. Multilevel Inheritance
3. Multiple Inheritance
4. Hierarchical Inheritance
5. Hybrid Inheritance
Single Inheritance
Single Inheritance have One base class and One derived class C++ single
inheritance only one class can be derived from the base class. Based on the
visibility mode used or access specify used while deriving, the properties of the
base class are derived. Accesses specify can be private, protected or public.
Diagram
Example
{ ..........
};
{ ...........
};
Example Program
#include<iostream>
using namespace std;
class aa
{
public:
void add()
{
int a=5,b=6,c;
c=a+b;
cout<<c;
}
};
class bb:public aa
{
public:
void sub()
{
int d=5, e=4, f;
f=d-e;
cout<<f;
}
};
int main()
{
bb obj;
obj.add();
obj.sub();
return 0;
};
Multilevel Inheritance
(One Base - One Derived - One or more than One Intermediate class)
Diagram
#include<iostream>
using namespace std;
class aa
{
public:
void add()
{
int a=5,b=6,c;
c=a+b;
cout<<c;
}
};
class bb:public aa
{
public:
void sub()
{
int d=5, e=4, f;
f=d-e;
cout<<f;
}
};
class cc:public bb
{
public:
void mul()
{
int g=5,h=6,i;
i=g*h;
cout<<i;
}
};
int main()
{
cc obj;
obj.add();
obj.sub();
obj.mul();
return 0;
};
Multiple Inheritance
More than One base class -One derived class
Diagram
Syntax
class A
{..........
};
class B
{ ...........
};
class C : acess_specifier A , access_specifier B // derived class from A and B
{...........
};
Example Program
#include<iostream>
using namespace std;
class aa
{
public:
void add()
{
int a=3,b=6,c;
c=a+b;
cout<<c;
}
};
class bb
{
public:
void sub()
{
int d=5, e=4, f;
f=d-e;
cout<<f;
}
};
class cc
{
public:
void mul()
{
int g=2,h=3,i;
i=g*h;
cout<<i;
}
};
class dd:publicaa,publicbb,public cc
{
public:
void div()
{
int j=6,k=2,l;
l=j/k;
cout<<l;
}
};
int main()
{
dd obj;
obj.add();
obj.sub();
obj.mul();
obj.div();
return 0;
}
Hierarchical Inheritance
Diagram
Syntax
class A // base class
{..............
};
class B : access_specifier A // derived class from A
{ ...........
};
class C : access_specifier A // derived class from A
{ ...........
};
class D : access_specifier A // derived class from A
{ ...........
};
Example Program
using namespace std;
class aa
{
public:
void add()
{
int a=3,b=6,c;
c=a+b;
cout<<c;
}
};
class bb:public aa
{
public:
void sub()
{
int d=5, e=4, f;
f=d-e;
cout<<f;
}
};
class cc:public aa
{
public:
void mul()
{
int g=2,h=3,i;
i=g*h;
cout<<i;
}
};
class dd:public aa
{
public:
void div()
{
int j=6,k=2,l;
l=j/k;
cout<<l;
}
};
int main()
{
bb ob;
ob.add();
ob.sub();
cc abc;
abc.add();
abc.mul();
dd obj;
obj.add();
obj.div();
return 0;
};
Hybrid Inheritance
Combination of More than One type of Inheritance
C++ hybrid inheritance is combination of two or more types of inheritance.
It can also be called multi path inheritance.
The hybrid combination of single inheritance and multiple inheritance.
Hybrid inheritance is used in a situation where we need to apply more than one
inheritance in a program.
Diagram
Syntax
class A
{ .........
};
class B : public A
{ ..........
};
class C
{ ...........
};
class D : public B, public C
{ ...........
};
Example Program
#include<iostream>
using namespace std;
class aa
{
public:
void add()
{
int a=3,b=6,c;
c=a+b;
cout<<c;
}
};
class bb : public aa
{
public:
void sub()
{
int d=5, e=4, f;
f=d-e;
cout<<f;
}
};
class cc
{
public:
void mul()
{
int g=2,h=4,i;
i=g*h;
cout<<i;
}
};
class dd : public bb, public cc
{
public:
void div()
{
int j=4,k=2,l;
l=j/k;
cout<<l;
}
};
int main()
{
dd obj;
obj.add();
obj.sub();
obj.mul();
obj.div();
return 0;
};
Constructor in an Inheritance
Constructor is a class member function with the same name as the class.
The main job of the constructor is to allocate memory for class objects.
Constructor is automatically called when the object is created.
Multiple Inheritance is a feature of C++ where a class can derive from
several(two or more) base classes. The constructors of inherited classes are
called in the same order in which they are inherited.
Syntax
class S: public A1, virtual A2
{
….
};
Here,
A2(): virtual base constructor
A1(): base constructor
S(): derived constructor
Example Program-Constructor with inheritance
#include<iostream>
using namespace std;
class A1
{
public:
A1()
{
cout<< "Constructor of the base class A1 \n";
}
};
class A2
{
public:
A2()
{
cout<< "Constructor of the base class A2 \n";
}
};
// Driver code
int main()
{
S obj;
return 0;
}
Friend Function
Function is defined as a friend function in C++, then the protected and private
data of a class can be accessed using the function.
By using the keyword friend compiler knows the given function is a friend
function.
For accessing the data, the declaration of a friend function should be done inside
the body of a class starting with the keyword friend.
o A global function
o A member function of another class
Syntax
class class_name
{
friend data_type function_name(argument/s); // syntax of friend function.
};
o The function is not in the scope of the class to which it has been declared
as a friend.
o It cannot be called using the object as it is not in the scope of that class.
o It can be invoked like a normal function without using the object.
o It cannot access the member names directly and has to use an object name
and dot membership operator with the member name.
o It can be declared either in the private or the public part.
#include<iostream.h>
#include<conio.h>
class ClassA
{
public:
int a;
};
class ClassB : virtual public ClassA
{
public:
int b;
};
class ClassC : virtual public ClassA
{
public:
int c;
};
classClassD : public ClassB, public ClassC
{
public:
int d;
};
void main()
{
ClassD obj;
obj.a = 10; //Statement 1
obj.a = 100; //Statement 2
obj.b = 20;
obj.c = 30;
obj.d = 40;
cout<< "\n A : "<< obj.a;
cout<< "\n B : "<< obj.b;
cout<< "\n C : "<< obj.c;
cout<< "\n D : "<< obj.d;
Output :
A : 100
B : 20
C : 30
D : 40
Example
Class student /*abstract class*/
{
Virtual void sum()=0; /*pure virtual function*/
};
Example
class Test // abstract class
{
public:
virtual void show() = 0;
};
Pure virtual function is also known as abstract class.
Example Program
#include<iostream.h>
#include<conio.h>
class BaseClass //Abstract class
{
public:
virtual void Display1()=0; //Pure virtual function or abstract function
virtual void Display2()=0; //Pure virtual function or abstract function
void Display3()
{
cout<<"\n\tThis is Display3() method of Base Class";
}
};
class DerivedClass : public BaseClass
{
public:
void Display1()
{
cout<<"\n\tThis is Display1() method of Derived Class";
}
void Display2()
{
cout<<"\n\tThis is Display2() method of Derived Class"
};
void main()
{
DerivedClass D;
}
Virtual Function
Syntax
class class- name
{
public:
virtual function-name()
{
}
};
Example
class bca
{
public:
virtual sum() // virtual function
{
}
};
Example program
#include <iostream>
using namespace std;
class Base
{
public:
virtual void print()
{
cout<< "Base Function" << endl;
}
};
class Derived : public Base
{
public:
void print()
{
cout<< "Derived Function" << endl;
}
};
int main()
{
Derived derived1;
Base* base1 = &derived1;
base1->print();
return 0;
}
Output
Derived Function
This Pointer
C++ this Pointer. Every object in C++ has access to its own address through
an important pointer called this pointer. This pointer is an implicit parameter
to all member functions. ... Friend functions do not have a this pointer, because
friends are not members of a class.
A friend function of a class is defined outside that class' scope but it has
the right to access all private and protected members of the class. Even though
the prototypes for friend functions appear in the class definition, friends are
not member functions.
Uses
‘this’ pointer is a constant pointer that holds the memory address of the
current object. ‘this’ pointer is not available in static member functions as static
member functions can be called without any object (with class name).
The this pointer holds the address of current object, in simple words you
can say that this pointer points to the current object of the class
Example Program:
#include <iostream.h>
class B;
class A
{
private:
int numA;
public:
A(): numA(12) { }
friend int add(A, B);
};
class B
{
private:
int numB;
public:
B(): numB(1) { }
friend int add(A , B);
};
int add(A objectA, B objectB)
{
return (objectA.numA + objectB.numB);
}
int main()
{
A objectA;
B objectB;
cout<<"Sum: "<< add(objectA, objectB);
return 0;
}
Inline Function
Inline function is powerful concept that is commonly used with classes. If
a function is inline, the compiler places a copy of the code of that function at each
point where the function is called at compile time.
Any change to an inline function could require all clients of the function to
be recompiled because compiler would need to replace all the code once again
otherwise it will continue with old functionality.
To inline a function, place the keyword inline before the function name and
define the function before any calls are made to the function. The compiler can
ignore the inline qualifier in case defined function is more than a line.
A function definition in a class definition is an inline function definition, even
without the use of the inline specifier.
1. If a function contains a loop. (for, while, do-while)
2. if a function has static variables.
3. Whether a function recurses.
4. If the return statement is absent from the function body and the return
type of the function is not void.
5. Whether a function uses a goto or switch statement.
Syntax
inline return_type function_name(parameters)
{
// function code?
}
Example Program
#include <iostream>
using namespace std;
inline int add(int a, int b)
{
return(a+b);
}
int main()
{
cout<<"Addition of 'a' and 'b' is:"<<add(2,3);A
return 0;
o In the inline function, we do not need to call a function, so it does not cause
any overhead.
o It also saves the overhead of the return statement from a function.
o It does not require any stack on which we can push or pop the variables as
it does not perform any function calling.
o An inline function is mainly beneficial for the embedded systems as it
yields less code than a normal function.
o If we use many inline functions, then the binary executable file also
becomes large.
o The use of so many inline functions can reduce the instruction cache hit
rate, reducing the speed of instruction fetch from the cache memory to
that of the primary memory.
o It also increases the compile-time overhead because whenever the
changes are made inside the inline function, then the code needs to be
recompiled again to reflect the changes; otherwise, it will execute the old
functionality.
o Sometimes inline functions are not useful for many embedded systems
because, in some cases, the size of the embedded is considered more
important than the speed.
UNIT -4
Files
Introduction to files
Files are used to store data in a storage device permanently. File handling
provides a mechanism to store the output of a program in a file and to perform
various operations on it.
● ofstream: This Stream class signifies the output file stream and is applied
to create files for writing information to files
● ifstream: This Stream class signifies the input file stream and is applied for
reading information from files
● fstream: This Stream class can be used for both read and write from/to
files.
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.
● This class contains open() and close() function.
6. ifstream:-
● This class provides input operations.
● It contains open() function with default input mode.
● Inherits the functions get(), getline(), read(), seekg() and tellg() functions from
the istream.
7. ofstream:-
● This class provides output operations.
● It contains open() function with default output mode.
● Inherits the functions put(), write(), seekp() and tellp() functions from the
ostream.
8. fstream:-
● This class provides support for simultaneous input and output operations.
● Inherits all the functions from istream and ostream classes through iostream.
9. filebuf:-
● Its purpose is to set the file buffers to read and write.
● We can also use file buffer member function to determine the length of the
file.
Opening a File
1. First is bypassing the file name in constructor at the time of object creation.
Syntax
● “w”– This mode specifies it is Open for writing. If the file exists, its contents
are overwritten.
If the file does not exist, it will be created.
● “a” – This mode specifies it is Open for append. Data is added to the end of
the file.
If the file does not exist, it will be created.
● “ab” – This mode specifies it is Open for append in binary mode. Data is
delivered to the end of the file.
If the file does not exist, it will be created.
● “r+” – This mode specifies it is Open for both reading and writing.
If the file does not exist, fopen() returns NULL.
● “rb+” – This mode specifies it is Open for both reading and writing in binary
mode.
If the file does not exist, fopen() returns NULL.
●“w+”– This mode specifies it is Open for both reading and writing.
If the file exists, its contents are overwritten. If the file does not exist, it will be
created.
●“wb+”- This mode specifies it is open for both reading and writing in binary
mode.
If the file exists, its contents are overwritten. If the file does not exist, it will be
created.
● “a+” – This mode specifies it is open for both reading and appending.
If the file does not exist, it will be created.
● “ab+” – This mode specifies it is Open for both reading and appending in
binary mode.
If the file does not exist, it will be created.
app Opens the file and appends all the outputs at the end
ate Opens the file and moves the control to the end ofthe file
myfile.open(“newfile.txt”, ios::out);
● ifstream ios::in
● ofstream ios::out
● fstream ios::in | ios::out
#include<iostream>
#include <fstream>
using namespace std;
int main()
{
fstream myfile;
myfile.open("myfile",ios::out);
if(!myfile)
{
cout<<"File creation failed";
}
else
{
cout<<"New file created";
myfile.close(); // Step 4: Closing file
}
return 0;
}
Output
Writing to a File
While doing C++ programming, you write information to a file from your
program using the stream insertion operator (<<) just as you use that operator to
output information to the screen. The only difference is that you use
an ofstream or fstream object instead of the cout object.
Example Program
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
fstream myfile;
myfile.open("myfile_write.txt",ios::out);
if(!myfile)
{
cout<<"File creation failed";
}
else
{
cout<<"New file created";
myfile<<"Learning File handling"; //Writing to file
myfile.close();
}
return 0;
}
Output
Reading a file
You read information from a file into your program using the stream
extraction operator (>>) just as you use that operator to input information from
the keyboard. The only difference is that you use an ifstream or fstream object
instead of the cin object.
To read a file we need to use ‘in’ mode with syntax ios::in. In the above
example, we print the content of the file using extraction operator >>. The output
prints without any space because we use only one character at a time, we need to
use getline() with a character array to print the whole line as it is.
Example Program
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
fstream myfile;
myfile.open("myfile_write.txt",ios::in);
if(!myfile)
cout<<"No such file";
}
else
{
char ch; while (!myfile.eof())
{
myfile>>ch;
cout<< ch;
}
myfile.close();
return 0;
}
Output
Close a File
Example Program
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
fstream myfile;
myfile.open("myfile.txt",ios::out);
myfile.close();
return 0;
}
Output:
C++ provides a special function, eof( ), that returns nonzero (meaning TRUE)
when there are no more data to be read from an input file stream, and zero
(meaning FALSE) otherwise. Rules for using end-of-file (eof( )): 1. Always test for
the end-of-file condition before processing data read from an input file stream.
The eof() method of ios class in C++ is used to check if the stream is has
raised any EOF (End Of File) error. It means that this function will check if this
stream has its eofbit set.
File Pointers
A pointer is used to handle and keep track of the files being accessed.
Every file maintains two pointers called get_pointer (in input mode file) and
put_pointer (in output mode file), which tells the current position where reading
or writing will take place with the use of opening modes and their respective
manipulators.
seekg():-
It is used to move the get pointer to the desired location concerning a reference
point.
Syntax: file_pointer.seekg (number of bytes ,Reference point);
Example: fin.seekg(10,ios::beg);
tellg():-
Syntax: file_pointer.tellg();
seekp():-
seekp() is used to move the put pointer to the desired location concerning a
reference point.
Example: fout.seekp(10,ios::beg);
tellp():-
Syntax: file_pointer.tellp();
ios::cur – These are used from the current position in the file.
Files Usage
Manipulators
Manipulators are helping functions that can modify
the input/output stream. It does not mean that we change the value of a variable,
it only modifies the I/O stream using insertion (<<) and extraction (>>) operators.
Types of Manipulators
ends: It is also defined in ostream and it inserts a null character into the
output stream. It typically works with std::ostrstream, when the associated
output buffer needs to be null-terminated to be processed as a C string.
flush: It is also defined in ostream and it flushes the output stream, i.e. it
forces all the output written on the screen or in the file. Without flush, the output
would be the same, but may not appear in real-time.
here put() write a single character to the associated stream. similarly the get()
function reads a single character from the associated stream. in the below
program show how these functions work on file. The program requests for a
string. on recieve the string, The program writes it, character by character, to the
file using the put() function in a for loop.
The function write() and read() unlike the function put() and get(), handled the
data in binary form. This means that the values are stored in the disk file in the
same format in which they are stored in the internal memory. in fig show how an
int value 2594 is stored, in the binary and character format. an int takes two
bytes to store its value in the binary form. irrespective of its size but a 4 digit in
will take four bytes to store it in the character form
The binary format is more accurate for storing the number as they are stored in
the exact internal representation. there are no conversions while saving the data
and therefore saving is much faster the binary input and output functions takes
the following form
Both have special ios parameters/flags, similar to the open function of the
ifstream.
Paramete
Explanation Example
r
Default setting: start from the infile.seekg(50,
beg
beginning ios::beg);
infile.seekg(-50,
end Start from the end of the file
ios::end);
infile.seekg(25,
cur Start from location of the pointer
ios::cur);
Example Program
string searchResult;
infile.seekg(10);
getline(infile, searchResult);
cout<< "10 from Beginning = " << searchResult << endl;
infile.seekg(5, ios::cur);
getline(infile, searchResult);
cout<< "5 from Current = " << searchResult << endl;
infile.seekg(-10, ios::end);
getline(infile, searchResult);
cout<< "-10 from End = " << searchResult << endl;
Output
10 from Beginning = llo
5 from Current= Hello
-10 from End = up|Hello
Error Handling During the File Operations in C++
The C++ programming language provides several built-in functions to
handle errors during file operations. The file error handling
int bad()
It returns a non-zero (true) value if an invalid operation is attempted or an
unrecoverable error has occurred. Returns zero if it may be possible to recover
from any other error reported and continue operations.
int fail( )
It returns a non-zero (true) value when an input or output operation has
failed.
int good()
It returns a non-zero (true) value when no error has occurred; otherwise
returns zero (false).
int eof( )
It returns a non-zero (true) value when end-of-file is encountered while
reading; otherwise returns zero (false).
int bad( )
The bad( ) function returns a non-zero (true) value if an invalid operation is
attempted or an unrecoverable error has occurred. Returns zero if it may be
possible to recover from any other error reported and continue operations.
Example Program
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
fstream file;
file.open("my_file.txt", ios::out);
string data;
file>> data;
if(!file.bad()){
cout<< "Operation not success!!!" <<endl;
cout<< "Status of the badbit: " << file.bad() << endl;
}
else {
cout<< "Data read from file - " << data << endl;
}
return 0;
}
Output
A C++ template is a powerful feature added to C++. It allows you to define the
generic classes and generic functions and thus provides support for generic
programming. Generic programming is a technique where generic types are used
as parameters in algorithms so that they can work for a variety of data types.
o Function templates
o Class templates
Function Templates:
We can define a template for a function. For example, if we have an add()
function, we can create versions of the add function for adding the int, float or
double type values.
Syntax
// body of function.
Ttype: It is a placeholder name for a data type used by the function. It is used
within the function definition. It is only a placeholder that the compiler will
automatically replace this placeholder with the actual data type.
#include <iostream>
using namespace std;
template<class T> T add(T &a,T &b)
{
T result = a+b;
return result;
}
int main()
{
int i =2;
int j =3;
float m = 2.3;
float n = 1.2;
cout<<"Addition of i and j is :"<<add(i,j);
cout<<'\n';
cout<<"Addition of m and n is :"<<add(m,n);
return 0;
}
Output:
Addition of i and j is :5
Addition of m and n is :3.5
Syntax
template<class T1, class T2,.....>
return_type function_name (arguments of type T1, T2....)
{
// body of function.
}
CLASS TEMPLATE
Class Template can also be defined similarly to the Function Template. When a
class uses the concept of Template, then the class is known as generic class.
Syntax
template<class Ttype>
class class_name
}
Ttype is a placeholder name which will be determined when the class is
instantiated. We can define more than one generic data type using a comma-
separated list. The Ttype can be used inside the class body.
class_name<type> ob;
where class_name: It is the name of the class.
type: It is the type of the data that the class is operating on.
Example Program
#include <iostream>
using namespace std;
template<class T>
class A
{
public:
T num1 = 5;
T num2 = 6;
void add()
{
std::cout << "Addition of num1 and num2 : " << num1+num2<<std::endl;
}
};
int main()
{
A<int> d;
d.add();
return 0;
}
Output:
Addition of num1 and num2 : 11
Syntax
template<class T1, class T2, ......>
class class_name
{
// Body of the class.
}
1. Containers: The STL provides a range of containers, such as vector, list, map,
set, and stack, which can be used to store and manipulate data.
2. Algorithms: The STL provides a range of algorithms, such as sort, find, and
binary_search, which can be used to manipulate data stored in containers.
3. Iterators: Iterators are objects that provide a way to traverse the elements of
a container. The STL provides a range of iterators, such as forward_iterator,
bidirectional_iterator, and random_access_iterator, that can be used with
different types of containers.
4. Function Objects: Function objects, also known as functors, are objects that
can be used as function arguments to algorithms. They provide a way to pass a
function to an algorithm, allowing you to customize its behavior.
5. Adapters: Adapters are components that modify the behavior of other
components in the STL. For example, the reverse_iterator adapter can be used
to reverse the order of elements in a container.
1. Algorithms
Algorithm
● Sorting
● Searching
● Important STL Algorithms
● Useful Array algorithms
● Partition Operations
2. Functors
The STL includes classes that overload the function call operator. Instances
of such classes are called function objects or functors. Functors allow the
working of the associated function to be customized with the help of parameters
to be passed. Must Read – Functors
3. Containers
Containers or container classes store objects and data. There are in total seven
standards “first-class” container classes and three container adaptor classes and
only seven header files that provide access to these containers or container
adaptors.
Classification of containers :
o Sequence containers
o Associative containers
o Derived containers
Sequence containers
● array: Static contiguous array (class template)
● vector: Dynamic contiguous array (class template)
● deque: Double-ended queue (class template)
● forward_list: Singly-linked list (class template)
● list: Doubly-linked list (class template)
Container Adaptors: provide a different interface for sequential containers.
● stack: Adapts a container to provide stack (LIFO data structure) (class
template).
● queue: Adapts a container to provide queue (FIFO data structure) (class
template).
● priority_queue: Adapts a container to provide priority queue (class
template).
Associative Containers: implement sorted data structures that can be quickly
searched (O(log n) complexity).
● Set: Collection of unique keys, sorted by keys
(class template)
● Map: Collection of key-value pairs, sorted by keys, keys are unique (class
template).
● multiset: Collection of keys, sorted by keys (class template)
● multimap: Collection of key-value pairs, sorted by keys
(class template)
Unordered associative containers
Unordered associative containers implement unsorted (hashed) data
structures that can be quickly searched (O(1) amortized, O(n) worst-case
complexity).
Iterators
o Iterators are used to traverse from one element to another element, a
process is known as iterating through the container.
o The main advantage of an iterator is to provide a common interface for all
the containers type.
o Iterators make the algorithm independent of the type of the container
used.
o Iterators provide a generic approach to navigate through the elements of a
container.
Syntax
<ContainerType> :: iterator;
<ContainerType> :: const_iterator;
begin(): The member function begin() returns an iterator to the first element of the
vector.
end(): The member function end() returns an iterator to the past-the-last element of a
container.
Iterator Categories
Iterators are mainly divided into five categories:
1. Input iterator:
o An Input iterator is an iterator that allows the program to read the
values from the container.
o Dereferencing the input iterator allows us to read a value from the
container, but it does not alter the value.
o An Input iterator is a one way iterator.
o An Input iterator can be incremented, but it cannot be decremented.
2. Output iterator:
o An output iterator is similar to the input iterator, except that it allows
the program to modify a value of the container, but it does not allow to
read it.
o It is a one-way iterator.
o It is a write only iterator.
3. Forward iterator:
o Forward iterator uses the ++ operator to navigate through the
container.
o Forward iterator goes through each element of a container and one
element at a time.
4. Bidirectional iterator:
o A Bidirectional iterator is similar to the forward iterator, except that it
also moves in the backward direction.
o It is a two way iterator.
o It can be incremented as well as decremented.
5. Random Access Iterator:
o Random access iterator can be used to access the random element of a
container.
o Random access iterator has all the features of a bidirectional iterator,
and it also has one more additional feature, i.e., pointer addition. By
using the pointer addition operation, we can access the random
element of a container.
Example Program
#include <iostream>
#include<iterator>
#include<vector>
using namespace std;
int main()
{
std::vector<int> v{1,2,3,4,5};
vector<int>::iterator itr;
for(itr=v.begin();itr!=v.end();itr++)
{
std::cout << *itr <<" ";
}
return 0;
}
Output:
12345
1. Learning curve: The STL can be difficult to learn, especially for beginners, due
to its complex syntax and use of advanced features like iterators and function
objects.
2. Lack of control: When using the STL, you have to rely on the implementation
provided by the library, which can limit your control over certain aspects of
your code.
3. Performance: In some cases, using the STL can result in slower execution
times compared to custom code, especially when dealing with small amounts
of data.
Exception Handling
try {
// protected code
} catch( ExceptionName e1 ) {
// catch block
} catch( ExceptionName e2 ) {
// catch block
} catch( ExceptionName eN ) {
// catch block
}
Throwing Exceptions
Catching Exceptions
The catch block following the try block catches any exception. You can
specify what type of exception you want to catch and this is determined by the
exception declaration that appears in parentheses following the keyword catch.
Try
{
// protected code
}
catch()
{
// code to handle ExceptionName exception
}
Example Program
#include <iostream>
using namespace std;
double division(int a, int b) {
if( b == 0 ) {
throw "Division by zero condition!";
}
return (a/b);
}
int main ()
{
int x = 50;
int y = 0;
double z = 0;
try {
z = division(x, y);
cout<< z << endl;
}
catch (const char* msg)
{
cerr<< msg << endl;
}
return 0;
}
C++ Exception Classes
Exception Description
This is an exception and the parent class of all standard C++
std::exception
exceptions.
std::bad_alloc This exception is thrown by a new keyword.
std::bad_cast This is an exception thrown by dynamic_cast.
std::bad_exception A useful device for handling unexpected exceptions in C++ programs.
std::bad_typeid An exception thrown by typeid.
std::logic_error This exception is theoretically detectable by reading code.
This is an exception thrown after using a mathematically invalid
std::domain_error
domain.
std::invalid_argument An exception thrown for using invalid arguments.
std::length_error An exception thrown after creating a big std::string.
std::out_of_range Thrown by at method.
std::runtime_error This is an exception that cannot be detected via reading the code.
Exception Description
This exception is thrown after the occurrence of a mathematical
std::overflow_error
overflow.
This exception is thrown when you attempt to store an out-of-range
std::range_error
value.
An exception thrown after the occurrence of mathematical
std::underflow_error
underflow.
Types of exceptions
1. Standard exceptions
These exceptions are a part of the C++ Standard Library and are defined in
the <exception> header. They are intended to provide a standard set of exception
classes for use in C++ programs and are designed to represent a wide range of
error conditions that may occur during the execution of a program. The standard
exceptions include std::logic_error,
2. Derived exceptions
The user in the application code defines these exceptions. They can be
derived from standard exceptions or a user-defined base class. User-defined
exceptions allow the programmer to indicate errors specific to the application
rather than relying on standard exceptions.
Example of User Define Exception
#include <iostream>
using namespace std;
class demo
{
};
int main()
{
try {
throw demo();
}
catch (demo d)
{
cout << "Caught exception of demo class \n";
}
}
Output:
Try-finally statement:
Syntax
C++Copy
// . . .
__try
{
// guarded code
}
__finally
{
// termination code
}
// . . .