Académique Documents
Professionnel Documents
Culture Documents
Whenever there is a function call, the control shifts to the func. declaration and after
complete execution , the control come backs to the main function, for achieving this lot of
overheads is faced by the system sas the current state needs to be saved somewhere ,
ex- registers,stack and this round trip is also called Context switching.
In order to reduce this effort inline functions are introduced where function definition is
pasted at the point of function call.
Disadvantage :
If function is large , then making a function inline can increase the size of program
Exceptions :
Member function which are defined inside a class are by default innline.
Member functions which are defined outside class are non-inline in nature , but we
can make them inline with keyword “inline”.
Friend Function :
int a = 2 , b = 3; ✔ int a = 2 , c = 3; ✔
int *p; ✔ Int &b = a; ✔
p = &a; ✔ b = c; ✔
int a = 2; ✔
int *p = &a; ✔ int a = 2; ✔
cout << *p; ✔ int &b = a; ✔
cout << b; ✔
POINTERS :
Pointer can point towards any memory location at any point.
At one point , pointer can point towards only one memory location.
A pointer and the variable towards which a pointer is pointing both should have same
data type.
Ex :
Integer Pointer can store address of only integer variable.
int *ptr;
int a = 10;
ptr = &a; ✔
float b = 2.3;
ptr = &b; ✘
Types of Pointers :
Wild Pointer
Null Pointer
void Pointer / Generic Pointer
Constant Pointer
Dangling Pointer
WILD POINTER :
Ex : -
int *p; //Uninitialised ✔
cout << *p; //Garbage Value ✔
cout << p; //Random address or Garbage Address ✔
NULL POINTER :
Ex : -
int *p = NULL;
cout << *p; ✘
count << p; ✔
VOID POINTER :
Void pointer can point towards any data typed variable / memory location.
In order to dereference a void pointer , typecasting with specific type of pointer is
required.
Pointer arithmetic rules are not applicable on void pointer.
void keyword is used to declare it.
Ex : -
int x = 10;
char ch = ‘A’;
void *gp;
gp = &x;
cout << *(int*)gp <<endl;
gp = &ch;
cout << *(char*)gp <<endl;
Output : -
10
A
CONSTANT POINTER :
Ex : -
int var = 60, var2 = 0;
int *const ptr = *var1; //Value is constant but address can be changed
//ptr = &var2; ✘
cout<< *ptr;
DANGLING POINTER :
Ex (COMPILE TIME) : -
int *ptr;
{
int y = 23;
ptr = &y;
}
//Here dangling pointer as v is no longer exist.
Ex (COMPILE TIME) : -
int* pvalue = NULL; //Pointer initialized with null.
pvalue = new int; //Request memory for the variable
Application : -
It is used in a situation , where name of the class’s data member and local are
same . It is used to distinguish both.
Ex : -
#include<iostream>
using namespace std;
class test{
int x;
public:
void setx(int x)
{
this->x=x;
}
void print()
{
cout<<"x="<<x<<endl;
cout<<"address of the current
object:"<<this<<endl;
}
};
int main(){
test c,c1,c2;
int x=20;
int x1=30;
int x2=40;
c.setx(x);
c.print();
c1.setx(x);
c1.print();
c2.setx(x);
c2.print();
}
Syntax to access it is :
<data_type_of_pointer><class_name>::<pointer_name>=&<class_name>::<dat
a_member>
t.*ptr=20;
Here .* is member dereferencing operator.
->* is also member dereferencing operator.
Syntax to access it : -
<return_type>(class_name::pointer_name)(argument)=&<class_name>::<funct
ion_name>
class Test{
public:
void show_msg();
};
void Test::show_msg(){
int main(){
void(Test::*fp)()=&Test::show_msg;
Test t;
(t.*fp)();
Test *ptr = new Test;
(ptr->*fp)();
Array : -
Collection of homogeneous elements.
Types : -
1D
Multidimensional array(2D,3D,.......)
1 D array : -
int a[max_size_of_array];
or directly initialising at the point of declaration.
Ex : int arr[] = { 1 , 2 , 3 };
2D array : -
int a[no . of rows][no. of columns];
int a[2][2] = { { 2 , 3 } , { 4 , 5 } };
int a1[2][2] = { 2 , 3 , 4 , 5 };
int a2[2][2] = { { 2 } , { 1 , 5 } };
int a3[2][2] = { 1 , 2 };
int a4[2][2] = { 0 };
int a5[][2] = { 1 , 2 , 3 , 4 };
UNIT - 3 :
Constructors and Destructors : -
It is member of class , which is automatically invoked (or called) as soon as
object of the class is created.
It has same name as that of class.
Constructor have no return type. (Not even void)
Constructor can accept arguments.
Constructor overloading is possible.
We can declare constructor inside and define outside of the class.
Constructor cannot be static.
Constructor are never inheritable(reusability).
They are initialize the data member of the class.
Internal Constructor : -
It is dummy or does nothing.
It is always called whenever object of class is created.
Types of constructor : -
Default constructor
Parameterized constructor
Copy constructor
Dynamic constructor
Default Constructors :
Type of constructor that accepts no argument.
Example : -
class example1{
int x , y;
public:
example(){
x = 2;
y = 3;
}
void display(){
cout << x << " " << y;
}
};
int main(){
example1 obj1;
obj1.display();
return 0;
Parameterized Constructor :
Type of Constructor that can accepts argument.
Example : -
#include<iostream>
using namespace std;
class example{
int x,y;
public:
example(int a,int b)
{
x = a;
y = b;
}
void display()
{
cout << endl << x << " " << y;
}
};
int main()
{
example obj1(2,3),obj2(4,5);
obj1.display();
obj2.display();
return 0;
}
#include<iostream>
using namespace std;
class example{
public:
example(int x,int y,int z)
{
};
int main()
{
example obj1(2,3,90);
return 0;
}
Features :
1. It will accept object as an argument by reference mechanism only.
2. It is also known as single argument constructor.
Example :
#include<iostream>
class Test {
int x , y;
public:
Test(int a , int b){
x = a;
y = b;
}
Test(Test &o){
x = o.x;
y = o.y;
}
display(){
cout << "\n" << x << " " << y;
}
};
int main(){
Test ob(2,3);
ob.display();
ob2.display();
ob3.display();
}
Note :
Passing object as an argument by value leads to infinite calls of copy constructor, so, by
reference needs to be used.
Constructor Overloading :
#include<iostream>
using namespace std;
class Test{
int x,y;
public:
Test(){
x = 10;
y = 12;
void display(){
cout << "Value of x and y : "<< x << " & " << y <<"\n";
};
int main(){
class Test{
int x,y;
public:
Test(int a , int b=0){ //Used the default
x = a;
y = b;
}
void display(){
cout << x << " " << y << "\n";
}
};
int main(){
Test obj(2);
obj.display();
Test obj2(2,3);
obj2.display();
}
class Test {
public:
Test(){}
Test(int a = 0){}
Destructor :
It is a member function of class which is automatically invoked as soon
as object is destroyed / or goes out of scope.
Features : -
It has same name as that of class.
It is preceded with ~ (tilde) symbol.
It does not have any return type (not even void).
Destructor cannot accept any argument.
It should be defined in the public section of class.
Destructor overloading is not allowed.
There should only one destructor function in the class.
We cannot access the current address of destructor in the class.
Objects with constructor and destructor cannot be used as members
of union.
Destructor are always involved in the reverse fashion as compared to
constructor order of execution (i.e. Last In First Out).
Example 1:-
#include <iostream>
class Test{
int x;
public:
Test(int n){
x = n;
cout << "\n Cons is called and val of x is "<< x;
}
~Test(){
cout << "\n Des is called and val of x is "<< x;
}
};
int main() {
Test ob(8);
Test ob2(89);
}
Example 2:
#include <iostream>
class Test{
int x;
private:
static int num_objects;
static int num_objects_destroyed;
public:
Test(){
num_objects++;
}
~Test(){
num_objects_destroyed++;
}
void show_data(){
cout << "\n\n Created : "<< num_objects;
cout << "\n Destroyed : "<< num_objects_destroyed;
cout << "\n Active : "<< num_objects - num_objects_destroyed;
}
};
int Test::num_objects = 0;
int Test::num_objects_destroyed = 0;
void my_func(){
Test s8,s9;
s9.show_data();
}
int main() {
Test s1,s2,s3;
{
s1.show_data();
Test s4;
{
Test s5;
s5.show_data();
}
}
s3.show_data();
my_func();
s2.show_data();
}
Output of above :
Created : 3
Destroyed : 0
Active : 3
Created : 5
Destroyed : 0
Active : 5
Created : 5
Destroyed : 2
Active : 3
Created : 7
Destroyed : 2
Active : 5
Created : 7
Destroyed : 4
Active : 3
Initialiser List :
It is used to initialise data member of a class.
Much Efficient as assignment operator is not used.
Other Applications :-
It is used to initialise non-static constant data member of class.
It is used to initialise reference data members.
It is used to distinguish data member of the class and local parameter of the member
function if there name are same.
Ex :
#include <iostream>
using namespace std;
class Test{
int x , y;
public:
Test( int a , int b) : x(a) , y(b) {};
void show(){
cout << "\n Value of x and y are : " << x << " " << y ;
}
};
int main(){
Stream :-
Flow of data (Sequence of bytes).
<fstream> is the header file.
There are 3 inbuilt classes
ifstream -----> input file stream
ofstream ----->output file stream
filestream ----->input/output
Note : After reading the file , close the file with close() member function.
Using fstream (ofstream) - Write to File , Creates the file if not exist.
Ex : -
#include <iostream>
#include <fstream>
#include <stdlib.h>
if(!ob){
Questions : -
Write a prog to read 3 integer from one file and write the largest integer into another file
#include<iostream>
#include<fstream>
#include<stdlib.h>
using namespace std;
int main()
{
int a[3];
ifstream obj1;
obj1.open("input1.txt");
if(!obj1)
{
cout<<"\nFile could not be opened for reading";
exit(1);
}
obj1>>a[0]>>a[1]>>a[2];
obj1.close();
ofstream obj2;
obj2.open("output1.txt");
if(!obj2)
{
cout<<"\nFile could not be opened for writing";
exit(1);
}
if(a[0]>a[1] && a[0]>a[2])
{
obj2<<"First Number Is Largest";
}
else if(a[1]>a[0] && a[1]>a[2])
{
obj2<<"Second Number Is Largest";
}
else
{
obj2<<"Third Number Is Largest";
}
cout<<"Successfully";
obj2.close();
return 0;
}
Ex:-
#include<iostream>
#include<fstream>
#include<stdlib.h>
using namespace std;
int main()
{
char data[100];
ifstream obj;
obj.open("first.cpp");
if(!obj)
{
cout<<"\nFile could not be opened for reading";
exit(1);
}
while(obj.eof()==0)
{
obj.getline(data,100);
cout<<data<<"\n";
}
obj.close();
return 0;
}
Ex 2:-
#include<iostream>
#include<fstream>
#include<stdlib.h>
using namespace std;
int main()
{
char data[100];
ifstream obj;
obj.open("first.cpp");
if(!obj)
{
cout<<"\nFile could not be opened for reading";
exit(1);
}
while(obj)
{
obj.getline(data,100);
cout<<data<<"\n";
}
obj.close();
return 0;
}
Ex : -
#include<iostream>
#include<fstream>
#include<stdlib.h>
using namespace std;
int main()
{
char data[100];
fstream obj,obj2;
obj.open("input3.txt",ios::in);//taking i/p from the file
if(!obj)
{
cout<<"\n error";
exit(1);
}
obj2.open("output3.txt",ios::out);//gives output to file
if(!obj2)
{
cout<<"\n error";
exit(1);
}
while(obj.eof()==0)
{
obj.getline(data,100);
obj2<<data<<endl;
}
obj.close();
obj2.close();
return 0;
}
Sequential input/output : -
get() and put(): They are used to read and write data into file character by character.
Write a prog to count number of vowels in a file and write count in another files
#include<fstream>
#include<stdlib.h>
#include<iostream>
int main(){
fstream ob;
char ch;
int count = 0;
ob.open("input.txt",ios::in);
if(!ob){
cout <<"ERror";
exit(1);
}
ch = ob.get();
while(ob){
ch = ob.get();
}
ob.close();
ob.open("out.txt",ios::out);
ob<<count;
ob.close();
return 0 ;
}
#include<fstream>
#include<stdlib.h>
#include<iostream>
int main(){
fstream ob,ob2;
char ch,ch2;
int count = 0;
ob.open("input1.txt",ios::in);
ob2.open("input2.txt",ios::in);
if(!ob||!ob2){
cout <<"ERror";
exit(1);
}
ch = ob.get();
ch2=ob2.get();
while(ob!=0||ob2!=0){
if(ch!=ch2){
cout<<"Not Equal";
exit(1);
ch = ob.get();
ch2=ob2.get();
}
cout <<"Equal";
#include<iostream>
#include<fstream>
using namespace std;
class employee{
private:
int emp_code;
char name[20];
int hra;
int da;
int ta;
public:
void read_data()
{
cout<<"\n\nEnter The Employee code:";
cin>>emp_code;
cout<<"\n\nEnter The Employee Name:";
cin>>name;
cout<<"\n\nEnter hra,da and ta\n";
cin>>hra>>da>>ta;
}
void show_data()
{
cout<<"\n\nThe Employee code:\n"<<emp_code;
cout<<"\n\nThe Employee Name:\n"<<name;
cout<<"\n\nhra,da and ta\n"<<hra<<endl<<da<<endl<<ta;
}
};
int main()
{
fstream file;
employee e[3],d[3];
file.open("employee",ios::out|ios::binary);
cout<<"\nEnter the detail of three employees";
cout<<"\n-----------------------------------";
for(int i=0;i<3;i++)
{
e[i].read_data();
file.write((char *)&e[i],sizeof(e[i]));
}
file.close();
file.open("employee",ios::in|ios::binary);
cout<<"\nThe detail of three employees";
cout<<"\n-----------------------------------";
for(int i=0;i<3;i++)
{
file.read((char *)&d[i],sizeof(d[i]));
d[i].show_data();
}
file.close();
}
Out,trunc,in,app are used with text file whereas ate,binary,nocreate,noreplace are use with
binary file.
Types of access:-
Sequential access
get() and put()
read() and write()
Random access
Moving the file pointer to any specific location inside file
File pointer manipulation function
Seek function :-
Seek function seekg() and seekp() can also be used with two arguments as follows:
seekg(offset,refposition);
seekp(offset,refposition);
String : -
Array of character
String class
Ex:-
string a;
a=”hello”;
string a(“hello”);
cout<<a;
string a(“hello”);
string b(a);
cout<<b;
string s(“hello”);
string s1=s;
cout<<s1;
Taking input from user:-
string s;
cout<<”\nEnter String”;
getline(cin,s);
char s[10];
cout<<”Enter String”;
cin.getline(s,10);
Or
cin.getline(s,10,’$’);
char s[10]=”hello”;
char s1[10];
s1=s; ✘
string s1(“hello”);
String s2;
s1=s2; allowed
string s1,s2;
s1==s2;
s1>=s2;
s1<=s2;
s1>s2;
s1<s2;
//Syllabus - String
File Handling
Constructor & Destructor
Operator Overloading
Operator Overloading : -
Associate additional meaning to the existing operator.
Extending the meaning of the existing operator. So, that it can
work on user defined data type.
Features of operator overloading : -
Only existing operator can be overloaded, we cannot create new operator
overloading.
It is a part of compile time polymorphism.
Some of the operator in c++ are already overloaded.
Ex. = &,=,>>,<<
For achieving operator overloading , we need to create operator function,
where entire overloading logic will be specified.
Operator function one of 2 types : -
1. Member function
2. Friend function
Member function 0 1
Friend function 1 2
class Number{
private:
int x, y, z;
public:
Number(int x, int y, int z){
this->x = x;
this->y = y;
this->z = z;
}
void operator-(){
x = -x;
y = -y;
z = -z;
}
void showData(){
cout << " x : " << x << "\n" << " y : " << y << "\n" << " z :
" << z << "\n";
};
int main(){
Number ob(1,2,3);
ob.showData();
-ob; //Can also be done explicitly as operator-()
ob.showData();
}
cout << " x : " << x << "\n" << " y : " << y << "\n" << " z :
" << z << "\n";
};
void operator-(Number ob){
cout << " x : " << -ob.x << "\n" << " y : " << -ob.y << "\n"
<< " z : " << -ob.z << "\n";
int main(){
Number ob(1,2,3);
ob.showData();
}
Write a program to overload logical NOT.
#include <iostream>
using namespace std;
class Number{
private:
int x, y;
public:
Number(int x, int y){
this->x = !x;
this->y = !y;
}
void operator!(){
x = !x;
y = !y;
}
void showData(){
cout << " x : " << x << "\n" << " y : " << y << "\n" ;
};
int main(){
Number ob(98,99);
ob.showData();
!ob; //Can also be done explicitly as operator!()
ob.showData();
}
Increment/Decrement
#include<iostream>
using namespace std;
class number{
int x,y;
public:
number(int a,int b)
{
x=a;
y=b;
}
void operator++(int)
{
cout<<"Value after post increment are "<<x++<<" "<<y++;
}
friend void operator--(number,int);
};
void operator--(number obj,int)
{
cout<<"Value after post decrement are "<<obj.x--<<" "<<obj.y--;
}
int main()
{
number n(4,5);
n++;
n--;
}
#include<iostream>
using namespace std;
class complex{
float x,y;
public:
complex()
{
x=0.0;
y=0.0;
}
complex(float a,float b)
{
x=a;
y=b;
}
complex operator+(complex obj)
{
complex temp;
temp.x=x+obj.x;
temp.y=y+obj.y;
return temp;
}
void showData()
{
cout<<x<<" + i"<<y;
}
};
int main()
{
complex o1(2.7,3.6), o2(4.1,5.7), o3;
o3=o1+o2;
// o3=o1.operator+(o2);
o3.showData();
}
Overloading relational and equality(==,!=) operator : -
#include<iostream>
using namespace std;
class rel{
int x;
public:
rel()
{
x=0;
}
rel(int a)
{
x=a;
}
bool operator>(rel obj)
{
if(x>obj.x)
{
return 1;
}
else
return 0;
}
friend bool operator!=(rel,rel);
};
bool operator!=(rel obj1,rel obj2)
{
if(obj1.x!=obj2.x)
{
return 1;
}
else
{
return 0;
}
}
int main()
{
rel o1(4),o2(8);
if(o1>o2)
{
cout<<"First number is greatest";
}
else
{
cout<<"Second number is greatest";
}
if(o1!=o2)
{
cout<<"\nNumber are not equal";
}
else
{
cout<<"\nNumber are equal";
}
}
For the following operator , we cannot write the friend operator function :
1. = (assignment operator)
2. ( ) (Parenthesis or function parentheses)
3. [ ] (Subscript Operator)
4. -> (Arrow Operator)
CASE 1 :
Obj1 + 10;✔
CASE 2 : 10 + obj1;✘
But , In the case of friend function, it is not mandatory to have user defined
operand in the left side
Such as :-
Case 1 : obj + 10 ✔ [operator+(o1,10)]
Case 2 : 10 + obj ✔ [operator+(10,o1)]
Such as : -
Ob + ob2; ✔
Ob1 + 10; ✔
10 + obj1; ✔
10 + 10; ✘ [here both basic type]
#include<iostream>
using namespace std;
class time{
int h,m;
public:
time()
{
h=m=0;
}
time(int t)
{
h=t/
60;
m=t%60;
}
void showData()
{
cout<<h<<" hrs "<<m<<" min";
}
};
int main()
{
int min;
cout<<"Enter Minutes\n";
cin>>min;
time t1;
t1=min; // constructor function will be called which will take min
as //argument value
t1.showData();
return 0;
}
#include<iostream>
using namespace std;
class dist{
int km,m;
public:
dist()
{
km=m=0;
}
dist(int d)
{
km=d/1000;
m=d%1000;
}
void showData()
{
cout<<km<<" km "<<m<<" m";
}
};
int main()
{
int meter;
cout<<"Enter distance in meters\n";
cin>>meter;
dist d1;
d1=meter; // constructor function will be called which will take
meter as argument value
d1.showData();
return 0;
}
#include<iostream>
using namespace std;
class circle{
float area;
public:
circle()
{
area=0;
}
circle(int r)
{
area=3.14*r*r;
}
void showData()
{
cout<<"Area of circle is "<<area;
}
};
int main()
{
float radius;
cout<<"Enter radius of circle\n";
cin>>radius;
circle d1;
d1=radius; // constructor function will be called which will take
radius as argument value
d1.showData();
return 0;
}
Example 2:
#include<iostream>
using namespace std;
class circle
{
float area;
public:
circle()
{
area=0.0;
}
circle(float r)
{
area=3.14*r*r;
}
void show_data()
{
cout<<"Area of Circle is"<<" "<<area;
}
};
int main()
{
float radius;
cout<<"\n Enter radius of Circle"<<endl;
cin>>radius;
circle c1;
c1=radius;
c1.show_data();
return 0;
}
Properties of Operator Function:
1. There will be no return type for the function
2. It does not take any argument
3. It should return the target type into which user defined type will be
converted
4. Operator function overloads cast operator
Class to basic:-
#include<iostream>
class Time{
private:
int h, m;
public:
Time(){
h = m = 0;
}
void get_Data(){
}
operator int(){
int t = h*60+m;
return t;
}
};
int main(){
double time;
Time t;
t.get_Data();
time = t;
Inheritance
Types of Inheritance:-
Single inheritance
Type/Mode of Inheritance
Private - - -
class <derived_class_name>:<mode_of_inheritance><base_class_name>;
Single_Inheritance_Private_mode
Example :
#include<iostream>
using namespace std;
class student{
private:
int roll_no;
protected:
char section[10];
public:
void getRno()
{
cout<<"\nEnter The Roll Number\n";
cin>>roll_no;
}
void showRno()
{
cout<<"\n Roll no\n"<<roll_no;
}
};
class record:private student{
private:
float fees;
public:
void getData()
{
getRno();
cout<<"\nEnter fees\n";
cin>>fees;
cout<<"\nEnter Section\n";
cin>>section;
}
void display()
{
showRno();
cout<<"\nFees\n"<<fees<<"\nSection\n"<<section;
}
};
int main()
{
record o;
o.getData();
o.display();
// o.getRno();
// o.showRno();
// o.roll_no=78;
}
Single_Inheritance_Protected_mode
#include<iostream>
using namespace std;
class student{
private:
int roll_no;
protected:
char section[10];
public:
void getRno()
{
cout<<"\nEnter The Roll Number\n";
cin>>roll_no;
}
void showRno()
{
cout<<"\nRoll no\n"<<roll_no;
}
};
class record:protected student{
private:
float fees;
public:
void getData()
{
getRno();
cout<<"\nEnter fees\n";
cin>>fees;
cout<<"\nEnter Section\n";
cin>>section;
}
void display()
{
showRno();
cout<<"\nFees\n"<<fees<<"\nSection\n"<<section;
}
};
int main()
{
record o;
o.getData();
o.display();
// o.getRno(); //it will not work
// o.showRno(); //it will not work
// o.roll_no=78; //it will not work (private data)
// strcpy(o.section,"k18cj"); //it will not work (private data)
}
roll_no is not accessible with the object of result or within result class,
because it is not inherited.
Single_Inheritance_Public_mode
#include<iostream>
using namespace std;
class student{
private:
int roll_no;
protected:
char section[10];
public:
void getRno()
{
cout<<"\nEnter The Roll Number\n";
cin>>roll_no;
}
void showRno()
{
cout<<"\nRoll no\n"<<roll_no;
}
};
class record:public student{
private:
float fees;
public:
void getData()
{
getRno();
cout<<"\nEnter fees\n";
cin>>fees;
cout<<"\nEnter Section\n";
cin>>section;
}
void display()
{
showRno();
cout<<"\nFees\n"<<fees<<"\nSection\n"<<section;
}
};
int main()
{
record o;
o.getData();
o.display();
// o.getRno(); //possible---public
// o.showRno(); //possible---public
// o.roll_no=78; //possible---public
// strcpy(o.section,"k18cj"); //it will not work (protected data)
}
If we create object of result class,we can access get_rno() and show_rno() inside
main() function, as they are part of public section of result class.
We cannot access Section with the help of result class object as it is a part of
protected section of result class.
#include<iostream>
using namespace std;
class base{
protected:
int a;
};
class derived:public base{
private:
int b;
public:
void getData()
{
cout<<"\nEnter value of a and b : \n";
cin>>a>>b;
}
void sum()
{
Multilevel : -
Example 1 :
#include<iostream>
using namespacen= std;
class X{
protected:
int a;
public:
void getDataX()
{
cout<<"Enter value of a\n";
cin>>a;
}
};
class Y:public X{
protected:
int b;
public:
void getDataY()
{
cout<<"Enter value of b\n";
cin>>b;
}
};
class Z:public Y{
private:
int c;
public:
void getDataZ()
{
cout<<"Enter value of c\n";
cin>>c;
}
void sum()
{
cout<<"sum = "<<a+b+c;
}
};
int main()
{
Z obj;
obj.getDataX();
obj.getDataY();
obj.getDataZ();
obj.sum();
}
Example 2 :
#include<iostream>
using namespace std;
class length{
protected:
int l;
};
class breadth:public length{
protected:
int b;
};
void result()
{
cout<<"volume = "<<l*b*h;
}
};
int main()
{
volume obj;
obj.get_data();
obj.result();
}
Multiple Inheritance : -
Example 1 :
#include<iostream>
using namespace std;
class M{
protected:
int m;
public:
void get_m(){
cin >> m;
}
};
class N{
protected:
int n;
public:
get_n(){
cin >> n;
}
};
public:
void display(){
};
int main(){
P obj;
obj.get_m();
obj.get_n();
obj.display();
Example 2 :
#include<iostream>
using namespace std;
class A{
protected:
int x;
};
class B{
protected:
int y;
};
class C{
protected:
int z;
};
public:
void input(){
void display(){
int l;
if (x > y && x > z)
l = x;
else if (y > x && y >z)
l = y;
else l = z;
}
};
int main(){
D obj;
obj.input();
obj.display();
HIERARCHICAL:
#include<iostream>
using namespace std;
class M{
protected:
int x;
public:
void set(int x){
this->x = x;
}
};
class N:public M{
public:
void display(){
cout << "\nFROM N " << x;
}
};
class O:public M{
public:
void display(){
cout << "\nFROM O " << x;
}
};
int main(){
O obj;
N obj2;
obj.set(45);
obj.display();
obj2.set(56);
obj2.display();
}
Example 2 :
#include<iostream>
using namespace std;
class Operation{
protected:
int x;
public:
void set(){
cout << "\n";
int x;
cin >> x;
this->x = x;
}
};
class Task1:public Operation{
public:
void display(){
cout << "\nSquare is " << x*x;
}
};
public:
void display(){
int fac = 1;
while(x!=0){
fac = fac*x;
x--;
}
cout << "\n Factorial is " << fac;
};
int main(){
Task1 obj;
Task2 obj2;
obj.set();
obj.display();
obj2.set();
obj2.display();
Hybrid inheritance:-
Ambiguities in inheritance:
Single inheritance there is no ambiguity.
Multiple = ambiguity may arise.
hybrid(multipath inheritance) = ambiguity may arise.
Hierarchical = no ambiguity
Multilevel = no ambiguity
Example 1:
#include<iostream>
using namespace std;
class b1{
public:
void show_data()
{
cout<<"\nIn the base class 1";
}
};
class b2{
public:
void show_data()
{
cout<<"\nIn the base class 2";
}
};
class d:public b1,public b2{
public:
/*
d()
{
cout<<"\nIn derived class constructor";
}
void display()
{
//b1::show_data();
//b2::show_data();
}
*/
};
int main()
{
d obj;
// obj.show_data();
// solution
obj.b1::show_data();
obj.b2::show_data();
// or
// obj.display();
}
If more than one base classes are having same named member function,
then on accessing that member function with the class object inside
main(), ambiguity error may arise.
Solution :
Use class name and scope resolution operator along with object, during
call of member function.
Function Overriding
#include<iostream>
using namespace std;
class B1
{
public:
void show_data()
{
cout<<"\n In the base calss 1";
}
};
class B2
{
public:
void show_data()
{
cout<<"\n In the base class 2";
}
};
class D:public B1,public B2
{
public:
void show_data()
{
cout<<"\n In derived class";
}
};
int main()
{
D obj;
obj.show_data();
obj.B1::show_data();
return 0;
}
Order of Execution
Base class constructor is called first and then derived class constructor.
the order of execution of destructor is opposite.
Single Inheritance: -
#include<iostream>
using namespace std;
class A{
int x;
public:
A(int a)
{
x=a;
cout<<"\n calling the base class parameterized"<<x;
}
~A()
{
cout<<"\n calling base class constructor";
}
};
class B: public A
{
int l;
public:
B(int p, int q):A(p)
{
l=q;
cout<<"\n calling derived class constructor"<<l;
}
~B()
{
cout<<"\n calling derived class destructor";
}
};
int main()
{
B obj(1,2);
}
#include<iostream>
using namespace std;
class M
{
protected:
int m;
public:
M(int x)
{
m=x;
cout<<"\nin M";
}
};
class N{
protected:
int n;
public:
N(int x)
{
n=x;
cout<<"\n in N";
}
};
class P:public M, public N{
int l;
public:
P(int p, int q, int r):M(r),N(r)
{
l=p;
cout<<"\n in P";
}
void display()
{
cout<<"\n m="<<m<<"n="<<n<<"l="<<l;
}
};
int main()
{
P o(3,2,1);
o.display();
}
Application
New is used to allocate the memory at the They are just used for memory
runtime as well as it is used to create allocation.
objects also
New will always return memory for specific They will also return generic
type pointer (void *)
#include<iostream>
#include<stdlib.h>
using namespace std;
int main()
{
int *p=NULL;
p= new int;
//*p=12;
if(p==NULL)
{
cout<<"\n Memory Allocation failure";
exit(1);
}
*p=12;
cout<<"Integer value stored is:"<<*p;
delete p;
cout<<"Integer value stored is:"<<*p;
cout<<"\n Memory deallocated";
return 0;
}
Q1. WAP to allocate array of elements & sum the array elements (DMA).
#include<iostream>
using namespace std;
int main()
{
int *arr,sum=0;
int size;
cout<<"\nEnter the size of integer array: ";
cin>>size;
arr=new int(size);
if(arr==NULL)
{
cout<<"\nError in memory allocation";
exit(1);
}
cout<<"Enter array elements:\n";
for(int i=0;i<size;i++)
{
cin>>arr[i];
sum+=arr[i];
}
cout<<"\nElements stored in array\n";
for(int i=0;i<size;i++)
{
cout<<arr[i]<<endl;
}
cout<<"\nSum = "<<sum;
delete []arr;
}
Q2. WAP to allocate array of elements & average the array elements (DMA).
#include<iostream>
using namespace std;
int main()
{
float *arr,sum=0.0;
float size;
cout<<"\nEnter the size of integer array: ";
cin>>size;
arr=new float(size);
if(arr==NULL)
{
cout<<"\n Error in memory allocation";
exit(1);
}
cout<<"Enter array elements:\n";
for(int i=0;i<size;i++)
{
cin>>arr[i];
sum+=arr[i];
}
cout<<"\n Average = "<<sum/size;
delete []arr;
}
#include<iostream>
using namespace std;
int main()
{
int *fact=NULL;
int *p=NULL;
p=new int;
fact=new int;
if(p==NULL || fact==NULL)
{
cout<<"\nMemory Allocation Failure";
exit(1);
}
cout<<"\nEnter The Number:";
cin>>*p;
*fact=1;
for(int i=1;i<=*p;i++)
{
*fact=*fact*i;
}
cout<<"\nFactorial is = "<<*fact;
delete fact,p;
}
Q2. Find Simple interest using DMA.
#include<iostream>
int main(){
float *si=NULL,*p=NULL,*r=NULL,*t=NULL;
si = new float;
p = new float;
r = new float;
t = new float;
delete p,si,r,t;
#include<iostream>
using namespace std;
int main()
{
double *ar=NULL,*sum=NULL;
int size;
cout<<"\nEnter The Size of the Array:\n";
cin>>size;
ar=new double(size); //[]
sum = new double;
if(ar==NULL || sum==NULL)
{
cout<<"\nError Allocating Size";
exit(1);
}
*sum=0.0;
cout<<"\nEnter The Element:\n";
for(int i=0;i<size;i++)
{
cin>>ar[i];
*sum+=ar[i];
}
cout<<"\nAverage is = "<<*sum/size;
delete []ar,sum;
}
};
void array::getData(int n)
{
size=n;
arr=new int(size);
cout<<"Enter The Value Of Array:\n";
for(int i=0;i<size;i++)
{
cin>>arr[i];
}
}
void array::getSum()
{
for(int i=0;i<size;i++)
{
sum+=arr[i];
}
}
void array::displayData()
{
cout<<"Sum Of Array is:"<<sum;
}
int main()
{
array obj;
obj.getData(5);
obj.getSum();
obj.displayData();
}
Dynamic constructor
If memory is allocated at runtime using new operator within the definition of
constructor, then that constructor becomes dynamic constructor.
Example of Program :
#include<iostream>
using namespace std;
class Array{
int *arr;
int size;
public:
Array(int);
void get_data(int n);
int get_sum();
void display_data();
~Array()
{
delete []arr;
}
};
Array::Array(int n){
size=n;
arr= new int[size];
}
void Array::get_data(int n)
{
for(int i=0;i<size;i++)
{
cin>>arr[i];
}
}
void Array::display_data()
{
cout<<"entered elements";
for(int i=0;i<size;i++)
{
cout<<arr[i]<<" ";
}
cout<<endl<<"sum of array elements "<<get_sum();
}
int Array:: get_sum()
{
int sum=0;
for(int i=0;i<size;i++)
{
sum+=arr[i];
}
return sum;
}
int main()
{
int s;
cout<<"enter size";
cin>>s;
Array a(s);
a.get_data(s);
a.display_data();
}
#include<iostream>
using namespace std;
class sample{
public:
sample(){
cout<<"constructor called"<<endl;
}
~sample(){
cout<<"destructor called"<<endl;
}
};
int main()
{
int n;
cout<<"enter number of objects";
cin>>n;
sample * obj=new sample[n];
delete[]obj;
DMA of string
#include<iostream>
#include<string.h>
using namespace std;
class string1{
private:
char* str;
public:
string1(char *s)
{
int len=strlen(s);
str= new char[len+1];
strcpy(str,s);
}
~string1(){
cout<<endl<<"deleting string";
delete [] str;
}
void display()
{
cout<<str;
}
};
int main()
{
string1 s("hello world");
cout<<"s==";
s.display();
}
Memory Leak
Allocation Failure :
UNIT - 5 ( Part 2 )
RUNTIME POLYMORPHISM
Pointer to base
And
Pointer to derived
rules :
1. Pointer to base can point base class object as well as derived class
object.
2. Pointer to derived class can point towards its own object only; it cannot
point toward base class object.
3. Pointer to base class can point towards derived class but it can access
only the members of derived class which are common in both the classes
ie it can access specific member of derived.
All decision are taken at compile time. During this compiler,is just looking at the
type of pointer. Focus is not on what type of address is passed to the base class
pointer if the base class type pointer is used, then compiler will always call base
class version of member function.
#include<iostream>
using namespace std;
class BC
{
public:
void printBC()
{
cout<<"\n printing in derived class\n";
}
void show()
{
cout<<endl<<"show to base class"<<endl;
}
};
class DC
{
public:
void printDC()
{
cout<<endl<<"printing in DC"<<endl;
}
void show()
{
cout<<endl<<"show in derived class"<<endl;
}
};
int main()
{
BC *bptr, base;
bptr=&base;
cout<<"bptr to base class";
bptr->show(); //derived class
DC derived,*dptr;
dptr = &derived; // base pointer can point toward derived
class
cout<<"bptr now points toward derived class";
dptr->show();
dptr=&derived;
cout<<"dptr is derived type pointer";
dptr->show();
dptr->printDC();
cout<<"using ((dc*))bprt \n";
((DC*)bptr)->show();
((DC*)bptr)->printDC();
return 0;
}
Virtual Function
Virtual functions help us to achieve late binding (Runtime Polymorphism) in
C++.As, with this function,binding is delayed upto runtime, and now,focus is not
on the type of pointer return what kind of address is passed to the pointer.
Rules:
Binding is delayed upto runtime,as now focus is not only on type of pointer,
Rather point of concern is what type of address is passed to the base pointer.
If base class’s object address is passed then the base version of member
function is called, otherwise derived class version is called
Code
#include<iostream>
using namespace std;
class base
{
public:
virtual void print()
{
cout<<" base class print";
}
virtual void show()
{
cout<<" base class show";
}
};
class derived: public base
{
public:
virtual void print()
{
cout<<" derived class print";
}
virtual void show()
{
cout<<" derived class show";
}
};
int main()
{
base b, *bptr;
derived d;
bptr=&b;
bptr->print();
bptr->show();
bptr=&d;
bptr->print();
bptr->show();
}
Syntax : -
virtual void show()=0;
void virtual show()=0;
Abstract Class:
A class which is having at least one pure virtual function is known as abstract
class.
CODE-
#include<iostream>
using namespace std;
class sample
{
public:
virtual void example()=0;
virtual void show()
{
cout<<"\nthis is sample show() of abstract class";
}
};
class derived1:public sample
{
public:
void example()
{
cout<<"c++";
}
void show()
{
cout<<"\nthis is sample show() of derived class";
}
};
int main()
{
sample *ptr;
derived1 obj1;
ptr=&obj1;
ptr->example();
ptr->show();
}
Exception: -
(Example of run time error)
Exception are run time anomalies or unusual condition that a program may
encounter while executing.
Eg.- division by zero, access to an array outside of its bounds, running
out of memory space.
Because expectations are outside the normal operation of a program,
default action is to write out an error message and terminate the
offending process.
Types of exception : -
TRY BLOCK :
Set of statements code which can generate the exception.
CATCH BLOCK :
Exception handling code is placed in catch block ( Useful message to be
used ).
Syntax : -
try
{
//code
throw <value>;
}
catch(type argument_name)
{
//error handling code
}
hh
#include<iostream>
using namespace std;
int main()
{
int a,b;
cout<<"\nEnter value of a and b:\n";
cin>>a>>b;
int x=a-b;
try
{
if(x!=0)//hit the exception
{
cout<<"Result(a/x)="<<a/x<<"\n";
}
else
{
throw x;//throw the exception
}
}
catch(int x)//catch the exception
{
cout<<"\nException caught: Divide by
zero\n"<<x;//handle the exception
}
return 0;
}
The
catch(...)
{
__________
}
NOTE:- Generic catch block must be used at last of all other catch blocks.
It is like the final option , always priority is given to other catch.
If it written or used first or below some specific catch block, then compile time
error may arise
Rethrowing an exception:-
Invoking the function that generate exception or using throw function
outside try block
#include<iostream>
using namespace std;
void divide(int x,int y,int z)
{
cout<<"\nWe are inside the function";
if(x-y!=0)
{
cout<<"\nResult = "<<z/(x-y);
}
else
{
throw (x-y);
}
}
int main()
{
try
{
cout<<"\nWe are inside try block";
divide(10,20,30);
divide(10,10,30);
}
catch(int i)
{
cout<<"\nCaught an exception: "<<i;
}
}
We can throw, object and there should be relevant catch block also,
which should catch the object typed exception and relevant message is
displayed on the screen.
Program Example :
#include<iostream>
#include<string.h>
#include<conio.h>
using namespace std;
class error{
int err_code;
char *err_desc;
public:
error(int c,char* d)
{
err_code=c;
err_desc=new char[strlen(d)+1];
strcpy(err_desc, d);
}
void err_display()
{
cout<<"\nError Code:"<<err_code<<"\nError
discription:"<<err_desc;
}
};
int main()
{
try
{
cout<<"\nPress Any Key: ";
getch();
error obj(99,"This is error");
throw obj;
}
catch(error e)
{
cout<<"\nException Caught Successfully";
e.err_display();
}
}
#include<iostream>
using namespace std;
int main()
{
int a[5]={1,2,3,4,5};
try
{
int i=0;
while(1)
{
cout<<a[i]<<endl;
i++;
if(i==5) //Better practice to use >=5 or >=n
{
throw i;
}
}
}
catch(int j)
{
cout<<"Array out of bond"<<j;
}
}
#include<iostream>
using namespace std;
int main()
{
int a;
cout<<"\nEnter the number\n";
cin>>a;
try
{
if(a%2==0)
throw a;
else
cout<<"\nEverything is fine";
}
catch(int a)
{
cout<<"\nException caught for even number:"<<a;
}
}
template<class t>
Or
template<typename t>
#include<iostream>
using namespace std;
template<class t>
t square(t num)
{
return(num*num);
}
int main()
{
int num1=3;
cout<<"\nSquare of "<<num1<<" = "<<square<int>(num1);
float num2=5.6;
cout<<"\nSquare of "<<num2<<" = "<<square<float>(num2);
double num3=123.456;
cout<<"\nSquare of "<<num3<<" = "<<square<double>(num3);
return 0;
}
Q2. WAP using function overloading & Template to calculate area of rectangle.
#include<iostream>
using namespace std;
template<class T>
int main(){
#include<iostream>
using namespace std;
int main(){
int num1 = 3;
float num2 = 4.54;
multiply <int,float> (num1,num2);
int num3= 9;
multiply <int,int> (num1,num3);
#include<iostream>
using namespace std;
template<class t1>
void swap1(t1 &num1,t1 &num2)
{
t1 temp=num1;
num1=num2;
num2=temp;
}
int main()
{
int inum1=3,inum2=5;
float fnum1=4.8,fnum2=-5.3;
char c1='A',c2='B';
cout<<"\nBefore Swapping:";
cout<<"\n inum1="<<inum1<<" and inum2="<<inum2;
cout<<"\n fnum1="<<fnum1<<" and fnum2="<<fnum2;
cout<<"\n c1="<<c1<<" and c2="<<c2;
swap1<int>(inum1,inum2);
swap1<float>(fnum1,fnum2);
swap1<char>(c1,c2);
cout<<"\nAfter Swapping:";
cout<<"\n inum1="<<inum1<<" and inum2="<<inum2;
cout<<"\n fnum1="<<fnum1<<" and fnum2="<<fnum2;
cout<<"\n c1="<<c1<<" and c2="<<c2;
}
#include<iostream>
using namespace std;
template <class t>
void display(t a)
{
cout<<"template display"<<a<<endl;
}
template<class t1, class t2, class t3>
void display(t1 a, t2 b, t3 c)
{
cout<<"template display "<<a<<","<<b<<","<<c<<endl;
}
void display(int x)
{
cout<<"explicit display "<<x<<endl;
}
void display(char y)
{
cout<<"explicit display "<<y<<endl;
}
int main()
{
display(100);
display(56.78);
display('a');
display(5.98,'b',89);
return 0;
}
#include<iostream>
using namespace std;
template <class t>
class abc
{
t a,b;
public:
abc(t x,t y)
{
a=x;
b=y;
}
t max1()
{
return(a>b?a:b);
}
};
int main()
{
abc<int>obj1(10,20);
cout<<"larger number "<<obj1.max1()<<endl;
abc<float>obj2(10.1,20.2);
cout<<"larger number "<<obj2.max1()<<endl;
abc<char>obj3('a','b');
cout<<"larger number "<<obj3.max1()<<endl;
return 0;
}
#include<iostream>
using namespace std;
template <class t1,class t2>
class abc
{
t1 a;
t2 b;
public:
abc(t1 x,t2 y)
{
a=x;
b=y;
}
void show1()
{
cout<<"values of a,b are"<<a<<" "<<b<<endl;
}
};
int main()
{
abc<float,int>obj1(10.2,20);
obj1.show1();
abc<int, char>obj2(10.1,'a');
obj2.show1();
return 0;
}
General Syntax :
<base_class_name> <name_of_generic_type>::<memebr_of_class>
PROGRAM EXAMPLE 1 :
#include<iostream>
#include<conio.h>
using namespace std;
template <class t>
class alpha{
protected:
t a;
public:
void check()
{
cout<<endl<<"hello";
}
};
template<class t, class t1>
class beta: public alpha<t>
{
private:
t1 b;
public:
void get()
{
cin>> alpha<t>::a>>b;
}
void display()
{
cout<<"a: "<< alpha<t>::a<<endl;
cout<<"b: "<< b;
alpha<t>::check();
}
};
int main()
{
beta<int, float> b1;
beta<float, int> b2;
cout<<"enter a,b";
b1.get();
b1.display();
cout<<"enter a,b";
b2.get();
b2.display();
#include<iostream>
using namespace std;
template<class t>
class abc{
t *a;
int size;
public:
abc()
{
cout<<"enter size of array";
cin>>size;
a= new t[size];
cout<<"enter the array values";
for(int i=0;i<size;i++)
cin>>a[i];
}
t sum1()
{
t sum=0;
for(int i=0;i<size;i++)
sum+=a[i];
return sum;
}
};
int main()
{
abc<int> obj1;
cout<<"sum is==>"<<obj1.sum1()<<endl;
abc<float> obj2;
cout<<"sum is==>"<<obj2.sum1()<<endl;
}
STL
Standard template library contains
o Containers
o Algorithms
o Iterators
1. CONTAINER:
It is an object that actually stores the data and it is a way data is organised in memory or
how the data is presented in memory.
2. ALGORITHMS:
They are procedure that are applied to container to process the data. example:
searching,sorting,etc.
3. ITERATORS:
Points to an element in an container and through this we can move to elements in an array.
We can use iterators to move through the contents of container.
It is an intermediate between algorithm and containers.
Relationship between Containers,Iterators and algorithm
2.AADA
2
Type of Containers:
1. Sequential container
Stores a set of elements in sequence, in other words each element
(except for the first and last in one) is preceded by one specific element
and followed by another
Eg are-<vector>
<list>
<deque>
i.<vector>: Is an expandable array(dynamic array) that can shrink or grow in size, but
still has the disadvantage of inserting or deleting of an element in middle. Allow
insertion and deletion at back.Very useful for random access(very fast).
ii.<list>: It is a double linked list (each element has its successor and a predecessors),
it is quick to insert and delete element but has slow random access.
iii.<deque>: It is a double-ended queue,that means one can insert and delete elements
from both ends, it is a kind of combination between a stack (last in first out) and a
queue (first in first out) and constitutes a compromise between a <vector> and <list>.
2. Associative container:
They are designed to store to support direct access to elements using
keys and they are non sequential.
The keys typically a number or a string, are used by a container
to arrange the stored elements in a specific order, for eg in a
dictionary the entries are ordered alphabetically.
There are 4 types of associative containers
i.Set
o It is a collection of unique keys only
ii.Multiset
o It is a collection of keys only , where keys can be
duplicate
iii.Map
o It is a collection of unique key-value pair
iv.Multimap
o It is a collection of key-value pairs, but pairs can be
duplicate i.e. A single key can have multiple values and
vica-versa
o E.g.- Dictionary of word
Features of Associate Container :
SET :
Stores a number of items which contain keys. The keys are the attributes
used to order the items, for example a set might store objects of the class.
MAP :
A <map> stores pairs of objects : a key object and an associated value
object. A <map> is somehow similar to an array except instead of
accessing its element with index numbers, you access them with indices of
an arbitrary type
<set> and <map> only allow one key of each value whereas
<multiset> and <multimap> allow multiple identical key values
3. Derived container
#include<iostream>
#include<vector>
using namespace std;
int main()
{
vector<int> v1(10);
// vector<int>v1;//zero size vector
cout<<"Size is\t"<<v1.size()<<endl;
for(int i=0;i<=9;i++)
{
v1[i]=i;
}
for(int i=10;i<=19;i++)
{
v1.push_back(i);
}
cout<<"\nSize is\t"<<v1.size()<<endl;
for(int i=0;i<=19;i++)
{
cout<<v1[i]<<"\t";
}
v1.pop_back();
v1.pop_back();
// use iterator to access the value
vector<int>::iterator v=v1.begin();
while(v!=v1.end())
{
cout<<"\nvalue of v = "<<*v;
v++;
}
}
#include<iostream>
#include<vector>
using namespace std;
int main()
{
vector<int> v1(9);
cout<<"Size is\t"<<v1.size()<<endl;
for(int i=0;i<=8;i++)
{
v1[i]=i;
}
vector<int>::iterator i=v1.begin();
i=i+3;
v1.insert(i,100);
for(int i=0;i<v1.size();i++)
{
cout<<v1[i]<<"\t";
}
cout<<endl;
// v1.erase(v1.begin());
v1.erase(v1.begin()+2,v1.begin()+5);
for(int i=0;i<v1.size();i++)
{
cout<<v1[i]<<"\t";
}
cout<<endl<<v1.size();
v1.clear();
cout<<"\n"<<v1.size();
}