Anda di halaman 1dari 93

Context switching & Inline Functions :

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.

Advantage of Inline functions :

 Execution will be faster.


 No overhead of context switching

Disadvantage :

 If function is large , then making a function inline can increase the size of program

Exceptions :

- Only smaller function can become inline.


- Function which are recursive in nature , cannot become inline.
- Function with loops , switch , goto statements cannot become inline.
- Inline is a keyboard

Inline Member Function :

 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”.

Static Data Member :

 Only one copy is created , which is shared by all objects.


 It is visible only within the class , but the lifetime is entire program.
 It is mandatory to define static data member outside class with the help of scope
resolution operator.
 They are initialized with default value zero.

Static Member Function :

 They belong to entire class , not to a particular object.


 Static member function can have only static data members inside their definition of
same class.
 They can be accessed with the help class name and scope resolution operator.

Friend Function :

 Private data of a class can be accessed.


 It is a non-member function
 There is no need of any object to access the friend function ( because it is a non-
member function)
 It will always accept object as an arrangement.
 It can be declared / defined in any section of class.

Pointer VS Reference Variable

1 ) Pointer can be initialised after its declaration , or we It is mandatory to initialise reference


can initialise it at the point of declaration. at the point of declaration.

Int *p; ✔ Int a = 10; ✔

Int a=0; ✔ int &b = a; ✔

p=&a; ✔ int a = 10; ✘


int &b; ✘
b = a; ✘

2 ) Reassignment / Re Initialisation of pointer is Not Allowed.


allowed.

int a = 2 , b = 3; ✔ int a = 2 , c = 3; ✔
int *p; ✔ Int &b = a; ✔
p = &a; ✔ b = c; ✔

3 ) Indirection or dereferencing operator is required for No need of dereference operator for


accessing the value pointed by the pointer. accessing the value.

int a = 2; ✔
int *p = &a; ✔ int a = 2; ✔
cout << *p; ✔ int &b = a; ✔
cout << b; ✔

4 ) It is possible to create null pointers. It is not allowed.

5 ) Pointer arithmetic is allowed. Not Allowed.

6 ) We can iterate through array element using Not possible in reference.


pointers.

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 :

Uninitialised pointer is a WILD POINTER.


Which can point towards any anonymous (Garbage) memory location.

Ex : -
int *p; //Uninitialised ✔
cout << *p; //Garbage Value ✔
cout << p; //Random address or Garbage Address ✔

NULL POINTER :

Pointer which is initialised with zero / null address value.


Ex : -
int *p = NULL; //Symbolic constant ✔
int *p = 0; ✔

 Null pointer cannot be dereferenced.


If we try to do that , run time error may be rise.

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 :

 It can point towards only one memory location.


 It is also called as READ ONLY

Ex : -
int var = 60, var2 = 0;
int *const ptr = *var1; //Value is constant but address can be changed
//ptr = &var2; ✘
cout<< *ptr;

DANGLING POINTER :

 It is a kind of element which is pointing towards already deleted or deallocated


memory location.
 It may arise in two cases : - Compile Time
- Runtime
- Solution to dangling pointer ( assign null address )

Ex (COMPILE TIME) : -
int *ptr;
{
int y = 23;
ptr = &y;
}
//Here dangling pointer as v is no longer exist.

cout << *ptr;


ptr = NULL; //Solution

Ex (COMPILE TIME) : -
int* pvalue = NULL; //Pointer initialized with null.
pvalue = new int; //Request memory for the variable

*pvalue = 23; //store value at allocated adr

cout << *pvalue << endl;

cout << pvalue << endl;

delete pvalue; //free up mem

cout << pvalue << endl;

pvalue = NULL; //No longer a dangling


this Pointer : -

 It holds the address of current object


 It is passed as an implicit parameter to non-static function , which holds the
address of current object involving that function.
 This is implicit pointer to an object.
 this->x=x in this first x is data member and another x is local variable
 This is a constant pointer

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();
}

Pointer to data member : -


int a=10;
int *p=&a;
cout<<*ptr;[10]

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.

Pointer to member function : -

Syntax to access it : -
<return_type>(class_name::pointer_name)(argument)=&<class_name>::<funct
ion_name>

using namespace std;

class Test{

public:
void show_msg();
};

void Test::show_msg(){

cout<<"\n Hello World!!";

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,.......)

Array can act as class/data member also.

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];

Methods to declare 2D array :

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;
}

Greatest Number using Constructor :

#include<iostream>
using namespace std;
class example{

public:
example(int x,int y,int z)
{

if(x>y && x>z) cout << "X"<< " " <<x;


else if(y>x && y>z) cout << "Y:"<< " " <<y;
else cout << "Z:" << " " <<z;

};
int main()
{
example obj1(2,3,90);
return 0;
}

 Copy Constructor (Single argument Constructor) :


It is used to initialise one object of the class with another object.

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>

using namespace std;

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();

Test ob2(ob); //Copied the Constructor

ob2.display();

Test ob3 = ob2; //Other way to call copy constructor

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;

Test(int x,int y){


this->x = x;
this->y = y;
}

void display(){

cout << "Value of x and y : "<< x << " & " << y <<"\n";

};

int main(){

Test ob; //Called default Cons.


ob.display();

Test ob2(9,15); //Called Parameterised


ob.display();

Constructor with Default Arguments :


#include<iostream>

using namespace std;

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();
}

There can be ambiguous condition :

class Test {
public:
Test(){}
Test(int a = 0){}

}; //Confusion of which Constructor to call.

 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>

using namespace std;

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>

using namespace std;

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(){

Test ob(2 , 3);


ob.show();

Test ob2 = Test(4 , 5);


ob2.show();
}

..: FILE HANDLING :..

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

Ways of opening file :-


 Using open() member function.
 Using inbuilt constructor of the class.

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>

using namespace std;


int main(){

ofstream ob; //ofstream ob(“Test.txt”);


ob.open("Test.txt");

if(!ob){

cout << "R/W Error!";


exit(1);
}

ob << "First test ..."; //bytes to write


ob.close();

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;
}

Detecting the end of the file : -


 With the help of eof() member function.
 With the help of file object.
 eof() member function belong to ios class
 It return false until unless end of the file is not achieved but as soon as end of the file
is reached,it return true.
 File object returns true until unless end of the file is not achieved,but on reaching the
end of the file it gives false.

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;
}

Prog to copy data line by line


#include<iostream>
#include<fstream>
#include<stdlib.h>
using namespace std;
int main()
{
char data[100];
ifstream obj;
obj.open("one.txt");
if(!obj)
{
cout<<"\nFile Cannot be Read";
exit(1);
}
ofstream obj2;
obj2.open("copy.txt");
if(!obj2)
{
cout<<"\nFile Cannot be Write";
exit(1);
}
while(obj)
{
obj.getline(data,100);
obj2<<data<<endl;
}
obj.close();
obj2.close();
cout<<"Copied";
}
fstream Class : -
 It is used for opening the file in read / write mode(both).

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.

They handle one character at one time.


 read() and write(): They are used to read and write object into file.They work in
binary mode
Used to handle series of the data(object) at one time.

Write a prog to count number of vowels in a file and write count in another files

#include<fstream>
#include<stdlib.h>
#include<iostream>

using namespace std;

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){

if(ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' ||


ch == 'u')
count++;

ch = ob.get();

}
ob.close();

ob.open("out.txt",ios::out);

ob<<count;

cout<<"\n Count of vowels written successfully";

ob.close();

return 0 ;
}

Wap to compare two files whether they identical or not.


Wap to count total no. of lines,space,character and tabs in a given file.
Wap to replace all space in a given file with ‘$’ and display output in another file.
FILE COMPARISON :

#include<fstream>
#include<stdlib.h>
#include<iostream>

using namespace std;

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";

Write() and read()


 write((char *)&v,sizeof(v))
 read((char *)arr,sizeof(arr))
 It work smoothly with binary file
 Binary files are faster as it is equivalent to computer language

#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();
}

ios::app : - Append to end of line


ios::ate :- go to end of the line and it can also modify data
ios::binary :- binary file
ios::in :- open file for reading
ios::nocreate :- open fail if file does not exist
ios::noreplace :- open fail if file already exist
ios::out :- open file for writing mode
ios::trunc :-delete content of file

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);

Offset - no. of bytes file pointer is to be moved


Refposition - specify position from where pointer to be moved

Takes one of 3 constants:


 Ios::beg start of the file
 Ios::cur current position of the pointer
 Ios::end end of file

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

It is possible to use relational operator between string objects for comparison.

string s1,s2;
s1==s2;
s1>=s2;
s1<=s2;
s1>s2;
s1<s2;

[ ] → subscript operator is applicable on string object


string obj(“hello”);
cout<<obj[0]; //h

Various member function in string class :-


 append() - It is use to add string at the end of another string.
Syntax : -
 string_object.append(string_object2);
 string_object.append(string_object2,index,length);
 insert() - It is used to insert substring inside given string at any given position.
Syntax : -
 string_object1.insert(index,string_object2);
 string_object1.insert(index,string_object2,index,length);
 replace()- Overwriting a part of the string with another string.
Syntax : -
 string_object1.replace(index,length,string_object2);
 string_object1.replace(index,length,string_object2,index,length);
 erase()- It is used to delete substring from a given string.
Syntax : -
 string_object.erase(index,length);
 clear()- It will delete all characters from a given string and final length of the
string will become zero.
Syntax : -
 string_object.clear();
 length()- It will display the count of total no.of character in a given string,
without counting the null character.
Syntax : -
 string_object.length();
 compare()- use to compare two strings
 substr()- It is use to extract the substring from given string
Syntax : -
 string_object.substr(index,length);
 find()- It will search for a given substring from left direction and if string is
found then it gives the index otherwise garbage value.
Syntax : -
 string_object.find(“substring_to_search”);
 rfind()- It will search for a given substring from right direction(reverse) and if
string is found then it gives the index otherwise garbage value.
 find_first_of()- It will return the index position where there is first occurence
of given character in any string.
 find_last_of()- It will return the index position where there is first occurence of
given character in any string.
Syntax : -
 string_object.find_first_of(‘character’);
 string_object.find_last_of(‘character’);
 at()- It will display the character at given index.
Syntax : -
 string_object.at(index);

//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

No. of argument Unary Binary

Member function 0 1

Friend function 1 2

 Actual meaning of the operator is never changed, only some additional


meaning is assigned to it.

Types of operator overloading : -


Write a prog to overload unary minus with help of operator member function
#include <iostream>

using namespace std;

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();
}

Using friend function : -


#include <iostream>
using namespace std;
class Number{
private:
int x, y, z;
public:
Number(int x, int y, int z){
this->x = x;
this->y = y;
this->z = z;
}
friend void operator-(Number);
void 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();

-(ob); //Can also be done explicitly as operator-()

}
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--;
}

Pre increment/ decrement


#include<iostream>
using namespace std;
class number{
int x,y;
public:
number(int a,int b)
{
x=a;
y=b;
}
void operator++()
{
cout<<"Value after pre increment are "<<++x<<" "<<++y;
}
friend void operator--(number);
};
void operator--(number obj)
{
cout<<"Value after pre decrement are "<<--obj.x<<" "<<--obj.y;
}
int main()
{
number n(4,5);
++n;
--n;
}
Wap to overload binary + operator using member function

#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";
}
}

Operator which cannot be overloaded:-


 sizeof
 ?:(Ternary or conditional operator)
 :: (Scope resolution)
 . (Member selection or dot operator)
 .*(member selection through pointer)

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)

Restrictions in operator overloading : -


 While overloading binary operator with the help of member function , it is
mandatory to have user defined data type (or class object) in the left side of
the binary operator expression, such as :-

CASE 1 :

Obj1 + 10;✔

Left side Right side

Obj1 is user defined

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)]

 While overloading binary operators [either by friend function / or by member


function] it is mandatory to have at least one operand to be user defined data
type

Such as : -

Ob + ob2; ✔
Ob1 + 10; ✔
10 + obj1; ✔
10 + 10; ✘ [here both basic type]

 Associativity and precedence of operators is never changed during operator


overloading.

 Original meaning of the operator is never completely changed,rather some


additional meaning is assigned to the operator, so that it can work on user
defined data types.

 Only existing operator can overloaded we cannot create new operator.


TYPE CONVERSION
1. Basic to Basic -> Converting one basic type to another
2. Basic to Class-> It is achieved through constructor function
3. Class to Basic-> It is achieved through operator function which is
overloading ()[cast] operator
4. Class to Class-> Possible with constructor function as well as
operator function

Basic to Class Example :

#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>

using namespace std;

class Time{

private:
int h, m;
public:
Time(){
h = m = 0;
}
void get_Data(){

cin >> h >> m;

}
operator int(){
int t = h*60+m;
return t;
}

};

int main(){

double time;

Time t;

t.get_Data();
time = t;

cout << sizeof(time);

cout << "Total : " << time;

Properties of operator function : -


 There will be no return type for the function.
 It does not take any argument.
 It should return the target type into which user defined type will be
converted.
 Operator function overload cast operator.

Inheritance

1. Deriving features of parent class and child class


2. Parent class/Base class/Super Child class/Derived class/sub
3. Application Reusability
4. No need of writing the same code from scratch
5. Programmer effort is reduced
6. Time is also saved as no need of writing same code again.

Types of Inheritance:-
 Single inheritance

Access Level / Access Specifier

Base Class Derived Class Friend Class

Private Yes No Yes

Protected Yes Yes Yes


Public Yes Yes Yes

Access Rights of Derived Class

Type/Mode of Inheritance

Private Protected Public

Private - - -

Protected Private Section Protected Section Protected Section

Public Private Section Protected Section Public Section

Syntax for derived class:

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;
}

After Creating object of derived , we can access following inside main() :


get_data();
display();

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)
}

After Creating object of derived , we can access following inside main() :


get_data();
display();

If we create object of result class, We cannot access section, get_rno()


and show_rno() in the main() function , they all are accessible inside
get_Data() and display() ,which are public data member functions of
result class.

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.

Create object if derived and access get_data() and sum()


Base Class : One Integer Data member (Protected)
Derived Class : One Integer Data member (Protected)

#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()
{

cout<<"\nSum is \n"<< a+b;


}
};
int main()
{
derived o;
o.getData();
o.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;
};

class height:public breadth{


protected:
int h;
};

class volume:public height{


public:
void get_data(){

cin >> l >> b >> h;

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;
}

};

class P:public M,public N{

public:
void display(){

cout << "m = " <<m << "\n";


cout << "n = " <<n << "\n";
cout << "m*n = " << m*n;
}

};

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;

};

class D:public A,public B,public C{

public:
void input(){

cin >> x >> y >> z;

void display(){

int l;
if (x > y && x > z)
l = x;
else if (y > x && y >z)
l = y;
else l = z;

cout << "Largest is "<< l;

}
};

int main(){

D obj;

obj.input();
obj.display();

HIERARCHICAL:

Example 1 : Create objects of N and O,and display() member functions with


both objects.

#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;
}

};

class Task2:public Operation{

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();
}

Ambiguity in multiple inheritance:

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

If functions with same signatures (i.e same name, arguments, order of


arguments) are defined in the base class as well as derived class, then on
creation of object of derived class, and if user calls the member function, then
always derived class version will be created, as it will override (or hide) the base
class version.

#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

Constructors and destructors are never inherited, operator member


functions , friend functions are also never inherited

Base class constructor is called first and then derived class constructor.
the order of execution of destructor is opposite.

Single Inheritance: -

 If a base class is having default constructor as well as derived


class is also having default constructors, then on creating object of
derived class, constructor of base class will be executed first then
derived and then destructor will be called in the reverse fashion.
 It is not mandatory for derived class to have default constructor ,
if base class have default constructor and vice versa
 If we have parameterised constructor in base class then it is
mandatory to have constructor in derived class.
 If base class is having parameterized constructor then it is
mandatory for derived class to have a parameterized constructor
which will pass, value to the parameterized constructor of base
using initializer list

code- with MultiLevel


#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();
}#include<iostream>
using namespace std;
class m{
protected:
int a;
public:
m(int x)
{
a=x;
cout<<"\nIn M";
}
};
class n{
protected:
int b;
public:
n(int x)
{
b=x;
cout<<"\nIn N";
}
};
class p:public m,public n{
int l;
public:
p(int p,int q,int r):m(r),n(q)
{
l=p;
cout<<"\nIn P";
}
void display()
{
cout<<"\nm="<<a<<"\nn="<<b<<"\np="<<l;
}
};
int main()
{
p obj(3,2,1);
obj.display();
}
nd#include<iostream>
using namespace std;
class a{
public:
a()
{
cout<<"\nCalling class a constructor";
}
~a()
{
cout<<"\nCalling class a destructor";
}
};
class b:public a{
public:
b()
{
cout<<"\nCalling class b constructor";
}
~b()
{
cout<<"\nCalling class b destructor";
}
};
class c:public b{
public:
c()
{
cout<<"\nCalling class c constructor";
}
~c()
{
cout<<"\nCalling class c destructor";
}
};
class d:public c{
public:
d()
{
cout<<"\nCalling class d constructor";
}
~d()
{
cout<<"\nCalling class d destructor";
}
};
int main()
{
d obj;
}

Example with Parameterized :

#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);
}

Order of constructor and destructor in multiple inheritance

In multiple inheritance the order of execution of constructor is dependent


upon the order of inheritance which means the class which is inherited first
constructor of that class will be invoked first. And the order of destructor is
opposite.

#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();
}

Constructor and destructor


Friends
Operator=( ) members
Private members

Dynamic memory allocation


Memory management operator

 now → allocation of memory


 Delete → deallocation of memory

Application

 To avoid the wastage of memory


DIFFERENCE BETWEEN NEW & MALLOC / CALLOC

New Malloc() / Calloc()


It is an operator These are functions

New is faster in execution,as it is an Functions are generally slower than


operator operator.

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

Constructor is called when new is used. Constructor is never called.

New will always return memory for specific They will also return generic
type pointer (void *)

Type casting is not required. Type casting to specific type is


required, as generic pointer is
returned.

Example 1 ( DMA with Single data ) :

#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;
}

DMA EXAMPLES WITH ARRAY

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;
}

Q.WAP to find factorial of a number using DMA.

#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>

using namespace std;

int main(){

float *si=NULL,*p=NULL,*r=NULL,*t=NULL;

si = new float;
p = new float;
r = new float;
t = new float;

if ( si == NULL || p == NULL || r == NULL || t == NULL ){

cout << "Error cannot allocate memory";


exit(1);

cout << "Enter P : ";


cin >> *p;
cout << "Enter R : ";
cin >> *r;
cout << "Enter T : ";
cin >> *t;

cout << "SI : " << (*p*(*r)*(*t))/100;

delete p,si,r,t;

Q3. Average of the Double data type array using DMA.

#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;
}

Dynamic memory allocation in class


#include<iostream>
using namespace std;
class array{
int *arr,size,sum=0;
public:
void getData(int n);
void getSum();
void displayData();
~array()
{
delete []arr;
cout<<"\nArray is Deleted";
}

};
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();
}

Dynamic array of object

#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

1. It is a problem with DMA..


2. It leads to stack overflow or system crash.
3. It happens when we forgot to delete/ deallocate the memory which was
allocated at runtime.

Allocation Failure :

If sufficient amount of memory is not available, then allocation failure may


occurs, and pointer will have NULL value, instead of any valid address.

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.

Early Binding(Compile type polymorphism):

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:

1. Virtual Function should be member of a class.


2. It cannot be static in nature.
3. It cannot become friend function to any class.
4. They are accessed with the help of pointer/ reference to a variable.
5. They should be defined in the public section of the class.
6. Virtual functions are always overridden as same signature of the
functions are used in base as well as derived class
7. Virtual function can be redefined in the derived class. But it is not
mandatory for derived class to redefine the virtual function. If the
virtual function is not defined then always base class implementation will
be called
8. Virtual keyword needs to used only one time,i.e inside base class only.No
need to write virtual keyword agan in the derived class.

Runtime polymorphism(late binding/ dynamic binding)

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();
}

Pure virtual function :


It is a type of virtual function with no definition in the base class, hence
it will be redefined in derived class.

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.

Features of Abstract Class:-


1. We cannot create object of abstract class, i.e. we can only create pointer
or reference to abstract base class.
2. Abstract class can have normal member function also, along with pure
virtual function.
3. It is mandatory to redefined the pure virtual function of abstract base
class in same derived class.
4. If the derived class is not redefined all pure virtual function of base,
then that derived class will also become abstract class.
5. Derived class which is inheriting abstract class is known as concrete
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 : -

1. Synchronous → Exceptions that are under the control of program(type


of exception that we can handle).

Error such as “out of range” and “overflow” are synchronous exceptions.

2. Asynchronous → Errors that are caused by events beyond the control of


the program (keyboard interrupts) are called asynchronous exceptions.
a. Exception handling in C++ is designed to handle only synchronous
exceptions.

Exception handling mechanism


1. Find the problem (hit the exception).
2. Inform that an error has occurred (Throw an exception).
3. Receive the error information. (Catch the exception)
4. Take corrective actions. (Handle the exception)

Keywords in exception Handling :


 try
 throw
 catch

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;
}

Multiple catch statement : -


#include<iostream>
using namespace std;
void test(int x)
{
try
{
if(x==1)
{
throw x; //int
}
else if(x==0)
{
throw 'x'; //char
}
else if(x==-1)
{
throw 1.0f; //float
}
else if(x==2)
{
throw "Caught a string value"; //string
}
cout<<"No suitable catch block found";
}
catch(char c)
{
cout<<"\nCaught a character";
}
catch(int m)
{
cout<<"\nCaught an integer";
}
catch(float a)
{
cout<<"\nCaught a float";
}
catch(const char* message)
{
cout<<"\n"<<message;
}
cout<<"\nEnd of try-catch system";
}
int main()
{
cout<<"Testing multiple catch";
cout<<"\nx==1";
test(1);
cout<<"\nx==0";
test(0);
cout<<"\nx==-1";
test(-1);
cout<<"\nx==2";
test(2);
return 0;
}

Catch all exception:-

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;
}
}

Catching class type as an exception or


Throwing user defined type exception

 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();
}
}

Array Index out of Bounds Exception:

#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;
}
}

Q. WAP to throw an exception , if the given input is even.

#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 in c++ or Generic programming : -


Function template:-

template<class t>
Or
template<typename t>

Q1. WAP to Calculate Square.

#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>

T rectangle(T num,T num2){


return (num*num2);
}

int main(){

int num1 = 3,num2 = 4;


cout << rectangle <int> (num1,num2) << endl;
float num3 = 5.6, num4 = 9.6;
cout << rectangle <float> (num3, num4) << endl;
float num5 = 1255.6, num6 = 583.2;
cout << rectangle <double> (num5, num6) << endl;
}

Q3. WAP to Product two numbers of different data types.

#include<iostream>
using namespace std;

template<class T1, class T2>

void multiply(T1 num,T2 num2){


cout << "Product : " << num*num2 << endl;
}

int main(){

int num1 = 3;
float num2 = 4.54;
multiply <int,float> (num1,num2);

int num3= 9;
multiply <int,int> (num1,num3);

double num5 = 1255.6;


multiply <double,float> (num5,num2);
}
Q4. WAP to swap the values of two variables using function template.

#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;
}

RULES OF OVERLOADING ( FUNCTION TEMPLATES )

 A template function may be overloaded either by a template


function or ordinary function of its name.
 Overloading resolution is accomplished as :
 Call an ordinary function that has an exact match.
 Call a template function that could be created with an
exact match.
- An error is generated of no match is found. Note that no
automatic conversion are applied to arguments on the template
functions.

Q. WAP of Function Template with Overloading.

#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;
}

Class templates can give generic types to :


 Data members of the class
 Member functions of the class. ( Return type, arguments and
Local Variables)
 Constructor functions. (Arguments and Local Variables).

Q. WAP to find Largest Number.

#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;
}

CLASS TEMPLATE WITH INHERITANCE

In order to access the member of base class inside derived class


with class template, following syntax needs to be followed :-

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();

Class Inheritance with template and dma-

#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;
}

..:: STANDARD TEMPLATE LIBRARY ::..


 Generic programing-
o Templates
 Functions
 Classes

 Collection of general purpose templetised classes or data


structure and functions or algorithms for storing and
processing data is known as standard template library(STL).

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.

EX: array, vector, stack, set, multi set.

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 :

1. Very fast in insertion and deletion.


2. Very efficient for searching.
3. Less efficient for sorting.
4. Bidirectional in nature.
5. Implemented as tree like structure.

 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

 The containers derived from different sequence containers.


 Derived Containers :
 Stacks
 Queues
 Priority Queues
 Also knowns as container adaptors.

..:: Vector Member Functions / Algorithms for Vector ::..


size() :- It will tell the current size of vector. (No. of elements, that are stored
currently).
push_back(value):- it adds the element at the end.
pop_back():- Deletes element from the last.
begin():- reference to first element.
end():- reference to last element.
insert(index,value):- It is used for inserting element at any given position.
erase(from index- inclusive,till index- exclusive):- it is used to delete range
of elements.
clear():- It is used to delete all elements of vector.

..:: PROGRAM EXAMPLE 1 FOR VECTOR ::..

#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++;
}
}

..:: PROGRAM EXAMPLE 2 FOR VECTOR ::..

#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();
}

..:: List Member Functions / Algorithms for List ::..

1. Push_back() :- Inserting elements at the end


2. push_front() :- Inserting elements at the beginning
3. pop_back() :- Deleting elements from end
4. pop_first() :- Deleting elements from beginning
5. sort() :- Sorting element in ascending order
6. reverse() :- Arranging the element in reverse order
7. merge() :- Combining the content of 2 list
8. empty() :- It will check whether list is empty or
not
9. begin() :- It gives reference of starting of list
10. end():- It gives the reference of end of list
11. clear():- It will delete all the elements
12. size() :- It will return the current size of
list.

PROGRAM FOR STL (LISTS) :


 LIST 1 PROGRAM(Click on it)

Anda mungkin juga menyukai