0% found this document useful (0 votes)
8 views138 pages

final notes cpp

Uploaded by

tanmaytati99
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
8 views138 pages

final notes cpp

Uploaded by

tanmaytati99
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 138

History of C++

The C++ language is an object-oriented programming language & is a combination of


both low-level & high-level language – a Middle-Level Language. The programming
language was created, designed & developed by a Danish Computer Scientist –
Bjarne Stroustrup at Bell Telephone Laboratories (now known as Nokia Bell Labs) in
Murray Hill, New Jersey. As he wanted a flexible & a dynamic language which was
similar to C with all its features, but with additionally of active type checking, basic
inheritance, default functioning argument, classes, etc. and hence C with Classes
(C++) was launched.
OOPs Concepts in C++

Object oriented programming is a way of solving complex problems by breaking


them into smaller problems using objects. Before Object Oriented Programming
(commonly referred as OOP), programs were written in procedural language, they
were nothing but a long list of instructions. On the other hand, the OOP is all about
creating objects that can interact with each other, this makes it easier to develop
programs in OOP as we can understand the relationship between them.

OOPS Concept Definitions

Now, let us discuss some of the main features of Object Oriented


Programming which you will be using in C++ (technically).

1. Objects
2. Classes
3. Abstraction
4. Encapsulation
5. Inheritance
6. Overloading
7. Exception Handling

Objects
Objects are the basic unit of OOP. They are instances of class, which have data
members and uses various member functions to perform tasks.
Class
It is similar to structures in C language. Class can also be defined as user defined
data type but it also contains functions in it. So, class is basically a blueprint for
object. It declare & defines what data variables the object will have and what
operations can be performed on the class's object.
Abstraction
Abstraction refers to showing only the essential features of the application and
hiding the details. In C++, classes provide methods to the outside world to access &
use the data variables, but the variables are hidden from direct access. This can be
done access specifier.
Encapsulation
It can also be said data binding. Encapsulation is all about binding the data variables
and functions together in class.
Inheritance
Inheritance is a way to reuse once written code again and again. The class which is
inherited is called base calls & the class which inherits is called derived class. So
when, a derived class inherits a base class, the derived class can use all the
functions which are defined in base class, hence making code reusable.
Polymorphism
It is a feature, which lets us create functions with same name but different
arguments, which will perform differently. That is function with same name,
functioning in different way. Or, it also allows us to redefine a function to provide its
new definition. You will learn how to do this in details soon in coming lessons.
Dynamic Binding:
In dynamic binding, the code to be executed in response to function call is decided at
runtime. C++ has virtual functions to support this.

Message Passing:
Objects communicate with one another by sending and receiving information to each
other.

Basic Data Types

The basic data types are integer-based and floating-point based. C++ language
supports both signed and unsigned literals.

The memory size of basic data types may change according to 32 or 64 bit operating
system.

Let's see the basic data types. It size is given according to 32 bit OS.

Type Typical Bit Width Typical Range

char 1byte -127 to 127 or 0 to 255

unsigned char 1byte 0 to 255

signed char 1byte -127 to 127


int 4bytes -2147483648 to 2147483647

unsigned int 4bytes 0 to 4294967295

signed int 4bytes -2147483648 to 2147483647

short int 2bytes -32768 to 32767

unsigned short int 2bytes 0 to 65,535

signed short int 2bytes -32768 to 32767

long int 8bytes -2,147,483,648 to 2,147,483,647

signed long int 8bytes same as long int

unsigned long int 8bytes 0 to 4,294,967,295

long long int 8bytes -(2^63) to (2^63)-1

unsigned long long int 8bytes 0 to 18,446,744,073,709,551,615

float 4bytes

double 8bytes

long double 12bytes

wchar_t 2 or 4 bytes 1 wide character

C++ Keywords

A keyword is a reserved word. You cannot use it as a variable name, constant name
etc. A list of 32 Keywords in C++ Language which are also available in C language
are given below.

auto break case char const continue default do


double else enum extern float for goto if

int long register return short signed sizeof static

struct switch typedef union unsigned void volatile while

C++ Operators

An operator is simply a symbol that is used to perform operations. There can be


many types of operations like arithmetic, logical, bitwise etc.

There are following types of operators to perform different types of operations in C


language.

o Arithmetic Operators
o Relational Operators
o Logical Operators
o Bitwise Operators
o Assignment Operator
o Unary operator
o Ternary or Conditional Operator

Basic Program in CPP


C++ program to add two numbers
#include <iostream.h>
int main()
{
int a, b, c;

cout << "Enter two integers to add\n";


cin >> a >> b;
c = a + b;
cout <<"Sum of the numbers: " << c << endl;
getch();
return 0;
}

Example of if-else-if

#include <iostream.h>
#include <conio.h>
int main()
{
int num;
cout<<"Enter an integer number between 1 & 99999: ";
cin>>num;
if(num <100 && num>=1)
{
cout<<"Its a two digit number";
}
else if(num <1000 && num>=100)
{
cout<<"Its a three digit number";
}
else if(num <10000 && num>=1000)
{
cout<<"Its a four digit number";
}
else
{
cout<<"number is not between 1 & 99999";
}
getch();
return 0;
}

Scope of Variables
All the variables have their area of functioning, and out of that boundary they don't
hold their value, this boundary is called scope of the variable. For most of the cases
it’s between the curly braces, in which variable is declared that a variable exists, not
outside it. We will study the storage classes later, but as of now, we can broadly
divide variables into two main types,

 Global Variables
 Local variables

Global variables
Global variables are those, which are once declared and can be used throughout the
lifetime of the program by any class or any function. They must be declared outside
the main() function. If only declared, they can be assigned different values at
different time in program lifetime. But even if they are declared and initialized at the
same time outside the main() function, then also they can be assigned any value at
any point in the program.

Local Variables
Local variables are the variables which exist only between the curly braces, in which
it’s declared. Outside that they are unavailable and leads to compile time error.
#include <iostream.h>
// Global variable declaration:
int g = 20;
int main ()
{
// Local variable declaration:
int g = 10;

cout << g; // Local


cout << ::g; // Global
getch();
return 0;
}

Output
This will give the output −
10
20

C++ Goto Statement

The C++ goto statement is also known as jump statement. It is used to transfer
control to the other part of the program. It unconditionally jumps to the specified
label.

#include<iostream.h>
#include<conio.h>
void main()
{
ineligible:
cout<<"You are not eligible to vote!\n";
cout<<"Enter your age:\n";
int age;
cin>>age;
if (age < 18){
goto ineligible;
}
else
{
cout<<"You are eligible to vote!";
}
getch();
}

Output:
You are not eligible to vote!
Enter your age:
16
You are not eligible to vote!
Enter your age:
7
You are not eligible to vote!
Enter your age:
22
You are eligible to vote!

sizeof() operator in C++


The sizeof() is an operator that evaluates the size of data type, constants, variable. It
is a compile-time operator as it returns the size of any variable or a constant at the
compilation time.

#include<iostream.h>
#include<conio.h>
void main()
{
// Determining the space in bytes occupied by each data type.
cout << "Size of integer data type : " <<sizeof(int)<< endl;
cout << "Size of float data type : " <<sizeof(float)<< endl;
cout << "Size of double data type : " <<sizeof(double)<< endl;
cout << "Size of char data type : " <<sizeof(char)<< endl;
getch();
}

Output:
Size of integer data type: 4
Size of float data type: 4
Size of double data type: 8
Size of char data type: 1
C++ Memory Management: new and delete
Arrays can be used to store multiple homogenous data but there are serious
drawbacks of using arrays.
You should allocate the memory of an array when you declare it but most of the time,
the exact memory needed cannot be determined until runtime.
The best thing to do in this situation is to declare an array with maximum possible
memory required (declare array with maximum possible size expected).
The downside to this is unused memory is wasted and cannot be used by any other
programs.
To avoid wastage of memory, you can dynamically allocate memory required during
runtime using new and delete operator in C++.

#include <iostream.h>
#include<conio.h>
int main()
{
int num;
cout << "Enter total number of students: ";
cin >> num;
float* ptr;

// memory allocation of num number of floats


ptr = new float[num];

cout << "Enter GPA of students." << endl;


for (int i = 0; i < num; ++i)
{
cout << "Student" << i + 1 << ": ";
cin >> *(ptr + i);
}

cout << "\nDisplaying GPA of students." << endl;


for ( i = 0; i < num; ++i)
{
cout << "Student" << i + 1 << " :" << *(ptr + i) << endl;
}

// ptr memory is released


delete [] ptr;
getch();
return 0;
}

Output
Enter total number of students: 4
Enter GPA of students.
Student1: 3.6
Student2: 3.1
Student3: 3.9
Student4: 2.9
Displaying GPA of students.
Student1 :3.6
Student2 :3.1
Student3 :3.9
Student4 :2.9

C++ Manipulators - endl, setw, setprecision, setf


Formatting output using manipulators
Formatted output is very important in development field for easily read and
understand.
C++ offers the several input/output manipulators for formatting, commonly used
manipulators are given below..

Manipulator Declaration in

endl iostream.h

setw iomanip.h

setprecision iomanip.h

setf iomanip.h

endl
endl manipulator is used to Terminate a line and flushes the buffer.
Difference b/w '\n' and endl
When writing output in C++,you can use either std::endl or '\n' to produce a newline,
but each has a different effect.
std::endl sends a newline character '\n' and flushes the output buffer.
'\n' sends the newline character, but does not flush the output buffer.
The distinction is very important if you're writing debugging messages that you really
need to see immediately, you should always use std::endl rather than '\n' to force the
flush to take place immediately.
The following is an example of how to use both versions, although you cannot see
the flushing occurring in this example.
#include <iostream.h>
int main()
{
cout<<"USING '\\n' ...\n";
cout<<"Line 1 \nLine 2 \nLine 3 \n";
cout<<"USING end ..."<< endl;
cout<< "Line 1" << endl << "Line 2" << endl << "Line 3" << endl;
return 0;
}
Output
USING '\n' ...
Line 1
Line 2
Line 3
USING end ...
Line 1
Line 2
Line 3

setw() and setfill() manipulators


setw manipulator sets the width of the filed assigned for the output.
The field width determines the minimum number of characters to be written in some
output representations. If the standard width of the representation is shorter than
the field width, the representation is padded with fill characters (using setfill).
setfill character is used in output insertion operations to fill spaces when results
have to be padded to the field width.
Syntax
setw([number_of_characters]);
setfill([character]);
Consider the example
#include <iostream.h>
#include <iomanip.h>
int main()
{
cout<<"USING setw() ..............\n";
cout<< setw(10) <<11<<"\n";
cout<< setw(10) <<2222<<"\n";
cout<< setw(10) <<33333<<"\n";
cout<< setw(10) <<4<<"\n";

cout<<"USING setw() & setfill() [type- I]...\n";


cout<< setfill('0');
cout<< setw(10) <<11<<"\n";
cout<< setw(10) <<2222<<"\n";
cout<< setw(10) <<33333<<"\n";
cout<< setw(10) <<4<<"\n";

cout<<"USING setw() & setfill() [type-II]...\n";


cout<< setfill('-')<< setw(10) <<11<<"\n";
cout<< setfill('*')<< setw(10) <<2222<<"\n";
cout<< setfill('@')<< setw(10) <<33333<<"\n";
cout<< setfill('#')<< setw(10) <<4<<"\n";
return 0;
}
Output
USING setw() ..............
11
2222
33333
4
USING setw() & setfill() [type- I]...
0000000011
0000002222
0000033333
0000000004
USING setw() & setfill() [type-II]...
--------11
******2222
@@@@@33333
#########4

Type Conversion in C++


Implicit type conversion
This is also known as automatic type conversion. This is done by the compiler
without any external trigger from the user. This is done when one expression has
more than one data type is present.
#include <iostream>
using namespace std;
int main() {
int a = 10;
char b = 'a';
a = b + a;
float c = a + 1.0;
cout << "a : " << a << "\nb : " << b << "\nc : " << c;
}

Output
a : 107
b:a
c : 108
#include <iostream>
using namespace std;
int main() {
double x = 1.574;
int add = (int)x + 1;
cout << "Add: " << add;
float y = 3.5;
int val = static_cast<int>(y);
cout << "\nvalue: " << val;
}

Output
Add: 2
value: 3
1. Classes and Objects

Class: A class in C++ is the building block that leads to Object-Oriented programming.
It is a user-defined data type, which holds its own data members and member
functions, which can be accessed and used by creating an instance of that class. A
C++ class is like a blueprint for an object

In C++, Object is a real world entity, for example, chair, car, pen, mobile, laptop etc. In
other words, object is an entity that has state and behavior. Here, state means data
and behavior means functionality. Object is a runtime entity, it is created at
runtime. Object is an instance of a class.

Create a Class

To create a class, use the class keyword:

Example

Create a class called "MyClass":

class MyClass { // The class


public: // Access specifier
int myNum; // Attribute (int variable)
string myString; // Attribute (string variable)
};

Create a Class with object

class Abc

int x;

void display()

// some statement

};

int main()

Abc obj; // Object of class Abc created

}
Access Control in C++

Now before studying how to define class and its objects, lets first quickly learn what
are access modifiers.
Access modifiers in C++ class defines the access control rules. C++ has 3 new
keywords introduced, namely,

1. public
2. private
3. protected

These access modifiers are used to set boundaries for availability of members of
class be it data members or member functions

Public Access Modifier in C++

Public, means all the class members declared under public will be available to
everyone. The data members and member functions declared public can be
accessed by other classes too.

class PublicAccess

// public access modifier

public:

int x; // Data Member Declaration

void display(); // Member Function decaration

Private Access Modifier in C++

Private keyword, means that no one can access the class members declared private,
outside that class. If someone tries to access the private members of a class, they
will get a compile time error. By default class variables and member functions are
private.

class PrivateAccess

// private access modifier

private:
int x; // Data Member Declaration

void display(); // Member Function decaration

Protected Access Modifier in C++

Protected, is the last access specifier, and it is similar to private, it makes class
member inaccessible outside the class. But they can be accessed by any subclass of
that class. (If class A is inherited by class B, then class B is subclass of class A. We
will learn about inheritance later.)

class ProtectedAccess

// protected access modifier

protected:

int x; // Data Member Declaration

void display(); // Member Function decaration

Defining Class and Creating Objects for student inside class definition

#include<iostream.h>

#include<conio.h>

class student

private:

char name[20],regd[10],branch[10];

int sem;

public:

void input()

cout<<"Enter Name:";

cin>>name;
cout<<"Enter Regdno.:";

cin>>regd;

cout<<"Enter Branch:";

cin>>branch;

cout<<"Enter Sem:";

cin>>sem;

void display()

cout<<"\nName:"<<name;

cout<<"\nRegdno.:"<<regd;

cout<<"\nBranch:"<<branch;

cout<<"\nSem:"<<sem;

void main()

student s;

s.input();

s.display();

getch();

Sample Input
Enter Name:Bikash
Enter Regdno.:123
Enter Branch:CS
Enter Sem:5
Sample Output
Name:Bikash
Regdno.:123
Branch:CS
Sem:5
Defining Class and Creating Objects for student outside class definition

#include<iostream.h>
#include<conio.h>

class student

private:

char name[20],regd[10],branch[10];

int sem;

public:

void input();

void display();

};

void student::input()

cout<<"Enter Name:";

cin>>name;

cout<<"Enter Regdno.:";

cin>>regd;

cout<<"Enter Branch:";

cin>>branch;

cout<<"Enter Sem:";

cin>>sem;

void student::display()

cout<<"\nName:"<<name;

cout<<"\nRegdno.:"<<regd;

cout<<"\nBranch:"<<branch;

cout<<"\nSem:"<<sem;

int main()

student s;
s.input();

s.display();

getch();

Accessing Public Data Members

Following is an example to show you how to initialize and use the public data
members using the dot (.) operator and the respective object of class.

#include<iostream.h>

#include<conio.h>

class Student

public:

int rollno;

string name;

};

int main()

Student A;

Student B;

// setting values for A object

A.rollno=1;

A.name="Adam";

// setting values for B object

B.rollno=2;

B.name="Bella";

cout <<"Name and Roll no of A is: "<< A.name << "-" << A.rollno;

cout <<"Name and Roll no of B is: "<< B.name << "-" << B.rollno;

Name and Roll no of A is: Adam-1


Name and Roll no of B is: Bella-2

Accessing Private Data Members

To access, use and initialize the private data member you need to create getter and
setter functions, to get and set the value of the data member.
The setter function will set the value passed as argument to the private data member,
and the getter function will return the value of the private data member to be used.
Both getter and setter function must be defined public.

Example :

#include<iostream.h>

#include<conio.h>

class Student

private: // private data member

int rollno;

public:

// public function to get value of rollno - getter

int getRollno()

return rollno;

// public function to set value for rollno - setter

void setRollno(int i)

rollno=i;

};

int main()
{

Student A;

A.rollono=1; //Compile time error

cout<< A.rollno; //Compile time error

A.setRollno(1); //Rollno initialized to 1

cout<< A.getRollno(); //Output will be 1

Example for Array of object

#include<iostream.h>

#include<conio.h>

class Employee

int Id;

char Name[25];

int Age;

long Salary;

public:

void GetData() //Statement 1 : Defining GetData()

cout<<"\n\tEnter Employee Id : ";

cin>>Id;

cout<<"\n\tEnter Employee Name : ";

cin>>Name;

cout<<"\n\tEnter Employee Age : ";

cin>>Age;

cout<<"\n\tEnter Employee Salary : ";


cin>>Salary;

void PutData() //Statement 2 : Defining PutData()

cout<<"\n"<<Id<<"\t"<<Name<<"\t"<<Age<<"\t"<<Salary;

};

void main()

int i;

Employee E[3]; //Statement 3 : Creating Array of 3 Employees

for(i=0;i<3;i++)

cout<<"\nEnter details of "<<i+1<<" Employee";

E[i].GetData();

cout<<"\nDetails of Employees";

for(i=0;i<3;i++)

E[i].PutData();

Output :

Enter details of 1 Employee

Enter Employee Id : 101

Enter Employee Name : Suresh

Enter Employee Age : 29

Enter Employee Salary : 45000

Enter details of 2 Employee


Enter Employee Id : 102

Enter Employee Name : Mukesh

Enter Employee Age : 31

Enter Employee Salary : 51000

Enter details of 3 Employee

Enter Employee Id : 103

Enter Employee Name : Ramesh

Enter Employee Age : 28

Enter Employee Salary : 47000

Details of Employees

101 Suresh 29 45000

102 Mukesh 31 51000

103 Ramesh 28 47000

Types of Class Member Functions in C++

We already know what member functions are, what they do, how to define member
function and how to call them using class objects. Now lets learn about some
special member functions which can be defined in C++ classes. Following are the
different types of Member functions:
Simple functions
Static functions
Const functions
Inline functions
Friend functions

Simple Member functions in C++

These are the basic member function, which dont have any special keyword like
static etc as prefix. All the general member functions, which are of below given form,
are termed as simple and basic member functions.

return_type functionName(parameter_list)

function body;

}
Static Member functions in C++

Static is something that holds its position. Static is a keyword which can be used
with data members as well as the member functions. A function is made static by
using static keyword with function name. These functions work for the class as
whole rather than for a particular object of a class.
It can be called using the object and the direct member access But, its more typical
to call a static member function by itself, using class name and scope
resolution :: operator.

For example:

class X

public:

static void f()

// statement

};

int main()

X::f(); // calling member function directly with class name

These functions cannot access ordinary data members and member functions, but
only static data members and static member functions can be called inside them.

Const Member functions in C++

Const keyword makes variables constant, that means once defined, there values
can't be changed.
When used with member function, such member functions can never modify the
object or its related data members.

// basic syntax of const Member Function

void fun() const

{
// statement

Inline functions in C++

All the member functions defined inside the class definition are by default declared
as Inline.
The syntax for defining the function inline is:

inline return-type function-name(parameters)

// function code

#include<iostream.h>

#include<conio.h>

inline int cube(int s)

return s*s*s;

int main()

cout << "The cube of 3 is: " << cube(3) << "\n";

return 0;

Output: The cube of 3 is: 27

class operation

int a,b,add,sub,mul;

float div;

public:
void get();

void sum();

void difference();

void product();

void division();

};

inline void operation :: get()

cout << "Enter first value:";

cin >> a;

cout << "Enter second value:";

cin >> b;

inline void operation :: sum()

add = a+b;

cout << "Addition of two numbers: " << a+b << "\n";

inline void operation :: difference()

sub = a-b;

cout << "Difference of two numbers: " << a-b << "\n";

inline void operation :: product()

mul = a*b;

cout << "Product of two numbers: " << a*b << "\n";

}
inline void operation ::division()

div=a/b;

cout<<"Division of two numbers: "<<a/b<<"\n" ;

int main()

cout << "Program using inline function\n";

operation s;

s.get();

s.sum();

s.difference();

s.product();

s.division();

return 0;

Output:

Enter first value: 45

Enter second value: 15

Addition of two numbers: 60

Difference of two numbers: 30

Product of two numbers: 675

Division of two numbers: 3

Friend functions in C++

Friend functions are actually not class member function. Friend functions are made
to give private access to non-class functions. You can declare a global function as
friend, or a member function of other class as friend.
Hence, friend functions can access private data members by creating object of the
class. Similarly we can also make function of some other class as friend, or we can
also make an entire class as friend class.
When we make a class as friend, all its member functions automatically become
friend functions.

Function Class Example

In this example we have two classes XYZ and ABC. The XYZ class has two private
data members ch and num, this class declares ABC as friend class. This means
that ABC can access the private members of XYZ, the same has been demonstrated
in the example where the function disp() of ABC class accesses the private
members num and ch. In this example we are passing object as an argument to the
function.

#include <iostream.h>

class XYZ

private:

char ch='A';

int num = 11;

public:

friend class ABC;

};

class ABC

public:

void disp(XYZ obj)

cout<<obj.ch<<endl;

cout<<obj.num<<endl;

};

int main() {

ABC obj;
XYZ obj2;

obj.disp(obj2);

return 0;

Output:

11

Friend Function:

Similar to friend class, this function can access the private and protected members
of another class. A global function can also be declared as friend as shown in the
example below:
Friend Function Example

#include <iostream.h>

#include<conio.h>

class XYZ

private:

int num=100;

char ch='Z';

public:

friend void disp(XYZ obj);

};

void disp(XYZ obj)

cout<<obj.num<<endl;

cout<<obj.ch<<endl;

int main()

XYZ obj;
disp(obj);

getch();

return 0;

Output:

100

Addition of members of two different classes using friend Function

#include <iostream.h>
#include<conio.h>
// forward declaration
class B;
class A
{
private:
int numA;
public:
A(): numA(12)
{
}
// friend function declaration
friend int add(A, B);
};

class B {
private:
int numB;
public:
B(): numB(1) { }
// friend function declaration
friend int add(A , B);
};

int add(A objectA, B objectB)


{
return (objectA.numA + objectB.numB);
}

int main()
{
A objectA;
B objectB;
cout<<"Sum: "<< add(objectA, objectB);
getch();
return 0;
}

Output
Sum: 13

#include <iostream.h>
#include<conio.h>
class Box
{
double width;
public:
friend void printWidth( Box box );
void setWidth( double wid );
};
void Box::setWidth( double wid ) {
width = wid;
}
void printWidth( Box box )
{
cout << "Width of box : " << box.width <<endl;
}
int main() {
Box box;
box.setWidth(10.0);
printWidth( box );
getch();
return 0;
}

Width of box : 10

Function overloading in C++

Function overloading is a C++ programming feature that allows us to have more than
one function having same name but different parameter list, when I say parameter
list, it means the data type and sequence of the parameters, for example the
parameters list of a function myfuncn(int a, float b) is (int, float) which is different
from the function myfuncn(float a, int b) parameter list (float, int). Function
overloading is a compile-time polymorphism.
Advantages of Function overloading
The main advantage of function overloading is to the improve the code
readability and allows code reusability.
C++ program to find volume of cube, cylinder, sphere by function overloading

#include<iostream.h>
#include<conio.h>
float vol(int,int);
float vol(float);
int vol(int);

int main()
{
int r,h,a;
float r1;
cout<<"Enter radius and height of a cylinder:";
cin>>r>>h;
cout<<"Enter side of cube:";
cin>>a;
cout<<"Enter radius of sphere:";
cin>>r1;
cout<<"Volume of cylinder is"<<vol(r,h);
cout<<"\nVolume of cube is"<<vol(a);
cout<<"\nVolume of sphere is"<<vol(r1);
return 0;
}
float vol(int r,int h)
{
return(3.14*r*r*h);
}
float vol(float r1)
{
return((4*3.14*r1*r1*r1)/3);
}
int vol(int a)
{

return(a*a*a);

Sample Input
Enter radius and height of a cylinder:8 12
Enter side of cube:2
Enter radius of sphere:3
Sample Output
Volume of cylinder is2411.52
Volume of cube is8
Volume of sphere is113.04

Processing Shopping List


#include<iostream.h>
#include<conio.h>
const m=50;
class ITEMS
{
int itemCode[m];
float itemPrice[m];
int count;

public:
void CNT (void)
{
count=0;
}
void getitem(void);
void displaysum(void);
void remove(void);
void displayitems(void);
};
//===================================
void ITEMS :: getitem(void)
{
cout<< “Enter item code :”;
cin>>itemCode[count];
cout<< “Enter item cost :”;
cin>>itemPrice[count];
count++;
}
void ITEMS :: displaysum(void)
{
float sum=0;
for(int i=0;i<count;i++)
{
sum=sum+itemPrice[i];
cout<<”\n Total value : “<<sum<<”\n”;
}
}
void ITEMS :: remove(void)
{
int a;
cout<<”Enter itemcode : “;
cin>>a;
for(int i=0;i<count;i++)
{
if(itemCode[i] == a)
{
itemPrice[i] = 0;
}
}
}

void ITEMS :: displayitems(void)


{
cout<<”\n Code Price\n”;
for(int i=0;i<count;i++)
{
cout<<”\n”<<itemCode[i];
cout<<”\n”<<itemPrice[i];
}
cout<<”\n”;
}

int main()
{
ITEMS order;
order.CNT();
int x;
do
{
cout <<”\n You can do the following”;
cout <<”\n Enter appropriate number”;
cout <<”\n1 : Add an item”;
cout <<”\n2 : Display total value”;
cout <<”\n3 : Delete an item”;
cout <<”\n4 : Display all items”;
cout <<”\n5 : Quit”;
cout <<”\n\nWhat is your option”;
cin>>x;
switch(x)
{
case 1 : order.getitem();break;
case 2 : order.displaysum();break;
case 3 : order.remove();break;
case 4 : order.displayitems();break;
case 5 : break;
default: cout<<”Error in input, try again\n”;
}
}
while(x != 5);
getch();
return 0;
}
Constructor

Constructor is a special member function of a class that initializes the object of the
class. Constructor name is same as class name and it doesn’t have a return type.

Constructor vs Member function

1) Constructor doesn’t have a return type. Member function has a return type.
2) Constructor is automatically called when we create the object of the class.
Member function needs to be called explicitly using object of class.
3) When we do not create any constructor in our class, C++ compiler generates a
default constructor and insert it into our code. The same does not apply to member
functions.

Special characteristics of Constructors:

1) They should be declared in the public section


2) They do not have any return type, not even void
3) They get automatically invoked when the objects are created
4) They cannot be inherited though derived class can call the base class
constructor
5) Like other functions, they can have default arguments
6) You cannot refer to their address
7) Constructors cannot be virtual
Syntax :
class temporary
{
private:
int x;
float y;
public:
// Constructor
temporary(): x(5), y(5.5)
{
// Body of constructor
}
... .. ...
};
int main()
{
Temporary t1;
... .. ...
}

Types of Constructors in C++

Constructors are of three types:


1. Default Constructor
2. Parameterized Constructor
3. Constructor Overloading
4. Copy Constructor

Default Constructors

Default constructor is the constructor which doesn't take any argument. It has no
parameter.
Syntax:
class Cube
{
public:
int side;
Cube()
{
side = 10;
}
};

int main()
{
Cube c;
cout << c.side;
}
#include <iostream.h>
#include<conio.h>
class Employee
{
public:
Employee()
{
cout<<"Default Constructor Invoked"<<endl;
}
};
int main(void)
{
Employee e1; //creating an object of Employee
Employee e2;
getch();
return 0;
}

Output:

Default Constructor Invoked

Default Constructor Invoked

Simple Constructor in Outside Class Declaration Example

#include <iostream.h>
#include<conio.h>
class Example
{
int a, b;
public:
//Constructor declaration
Example();
void Display()
{
cout << "Values :" << a << "\t" << b;
}
};

// Constructor definition outside Class


Example::Example ()
{
// Assign Values in Constructor
a = 10;
b = 20;
cout << "Im Constructor : Outside Class\n";
}

int main()
{
Example Object();
cout << "Simple Constructor Outside Class Declaration Example Program In C++\n";
// Constructor invoked.
Object.Display();
getch();
return 0;
}

C++ Parameterized Constructor

A constructor which has parameters is called parameterized constructor. It is used


to provide different values to distinct objects.
Let's see the simple example of C++ Parameterized Constructor.
#include <iostream>
class Point {
private:
int x, y;
public:
// Parameterized Constructor
Point(int x1, int y1)
{
x = x1;
y = y1;
}

int getX()
{
return x;
}
int getY()
{
return y;
}
};

int main()
{
// Constructor called
Point p1(10, 15);
// Access values assigned by constructor
cout << "p1.x = " << p1.getX() << ", p1.y = " << p1.getY();
return 0;
}

Output:

p1.x = 10, p1.y = 15

#include<iostream>
#include<conio.h>
class Prime {
//Member Variable Declaration
int a, k, i;
public:
// Parameterized Constructor definition
Prime(int x)
{
a = x;

k = 1;
for (i = 2; i <= a / 2; i++)
{
if (a % i == 0)
{
k = 0;
break;
}
else
{
k = 1;
}
}
}
void show() {
if (k == 1)
cout << a << " is Prime Number.";
else
cout << a << " is Not Prime Numbers.";
}
};
int main()
{
int a;
cout << "Simple Parameterized Constructor for Prime Number Example Program in
C++\n";
cout << "\nEnter the Number:";
cin>>a;
Prime obj(a);
obj.show();
getch();
return 0;
}

Simple Parameterized Constructor for Prime Number Example Program in C++

Enter the Number: 7

7 is Prime Number.

Simple Parameterized Constructor for Prime Number Example Program in C++

Enter the Number:10

10 is Not Prime Numbers.

Constructor Overloading

#include <iostream.h>
class ABC
{
private:
int x,y;
public:
ABC () //constructor 1 with no arguments
{
x = y = 0;
}
ABC(int a) //constructor 2 with one argument
{
x = y = a;
}
ABC(int a,int b) //constructor 3 with two argument
{
x = a;
y = b;
}
void display()
{
cout << "x = " << x << " and " << "y = " << y << endl;
}
};

int main()
{
ABC cc1; //constructor 1
ABC cc2(10); //constructor 2
ABC cc3(10,20); //constructor 3
cc1.display();
cc2.display();
cc3.display();
return 0;
}

Output

x = 0 and y = 0

x = 10 and y = 10

x = 10 and y = 20

Copy Constructor:

A copy constructor is a member function which initializes an object using another


object of the same class.
#include<iostream.h>
#include<conio.h>
class Example
{
int a, b;
public:
Example(int x, int y)
{
a = x;
b = y;
cout << "\nIm Constructor";
}
Example(const Example & obj)
{
a = obj.a;
b = obj.b;
cout << "\nIm Copy Constructor";
}
void Display()
{
cout << "\nValues :" << a << "\t" << b;
}
};

int main() {
//Normal Constructor Invoked
Example Object(10, 20);

//Copy Constructor Invoked - Method 1


Example Object2(Object);

//Copy Constructor Invoked - Method 2


Example Object3 = Object;
Object.Display();
Object2.Display();
Object3.Display();
getch();
return 0;
}

Sample Output
Im Constructor
Im Copy Constructor
Im Copy Constructor
Values :10 20
Values :10 20
Values :10 20

Destructors in C++

Destructor is a member function which destructs or deletes an object.


When is destructor called?
A destructor function is called automatically when the object goes out of scope:
(1) the function ends
(2) the program ends
(3) a block containing local variables ends
(4) a delete operator is called
How destructors are different from a normal member function?
Destructors have same name as the class preceded by a tilde (~)
Destructors don’t take any argument and don’t return anything

There can only one destructor in a class with class name preceded by ~, no
parameters and no return type.

#include<iostream>
#include<conio.h>

class BaseClass
{
public:
//Constructor of the BaseClass
BaseClass() {
cout << "Constructor of the BaseClass : Object Created"<<endl;
}

//Destructor of the BaseClass

~BaseClass()
{
cout << "Destructor of the BaseClass : Object Destroyed"<<endl;
}
};

int main ()
{
BaseClass des;
getch();
return 0;
}

Memory Allocation for Objects:

Example:
#include <iostream>

class Box
{
public:
Box()
{
cout << "Constructor is called!" <<endl;
}
~Box()
{
cout << "Destructor is called!" <<endl;
}
};
void main( )
{
Box* myBoxArray = new Box[4];

delete [] myBoxArray; // Delete array


getch();
}

Output:
Constructor is called!
Constructor is called!
Constructor is called!
Constructor is called!
Destructor is called!
Destructor is called!
Destructor is called!
Destructor is called!
C++ Operators Overloading

Operator overloading is a compile-time polymorphism in which the operator is


overloaded to provide the special meaning to the user-defined data type. Operator
overloading is used to overload or redefines most of the operators available in C++.
It is used to perform the operation on the user-defined data type. For example, C++
provides the ability to add the variables of the user-defined data type that is applied
to the built-in data types.

Operator Overloading can be done by using three approaches

1. Overloading unary operator.


2. Overloading binary operator.
3. Overloading binary operator using a friend function.

Overloading Unary Operator

Let us consider the unary ‘ – ‘ operator. A minus operator when used as a unary it
requires only one operand. We know that this operator changes the sign of an
operand when applied to a basic data variable. Let us see how to overload this
operator so that it can be applied to an object in much the same way as it is applied
to an int or float variable. The unary minus, when applied to an object, should
decrement each of its data items.

#include <iostream>
class Height
{
public:
int feet, inch;
Height(int f, int i)
{
feet = f;
inch = i;
}
void operator-()
{
feet--;
inch--;
cout << "Feet & Inches after decrement: " << feet << " ' " << inch <<endl;
}
};
int main()
{
Height h1(6, 2);
-h1;
return 0;
}

Output
Feet & Inches after decrement: 5’1

#include<iostream>
using namespace std;

class NUM
{
private:
int n;

public:
//function to get number
void getNum(int x)
{
n=x;
}
//function to display number
void dispNum(void)
{
cout << "value of n is: " << n;
}
//unary - operator overloading
void operator - (void)
{
n=-n;
}
};

int main()
{
NUM num;
num.getNum(10);
-num;
num.dispNum();
cout << endl;
return 0;

Output
value of n is: -10

#include<iostream>
class Numbers
{
int x, y, z;
public:
void accept()
{
cout<<"\n Enter Three Numbers";
cout<<"\n --------------------------";
cout<<"\n First Number : ";
cin>>x;
cout<<"\n Second Number : ";
cin>>y;
cout<<"\n Three Number : ";
cin>>z;
cout<<"\n --------------------------";
}
void display()
{
cout<<" ";
cout<<x<<"\t"<<y<<"\t"<<z;
}
void operator-()
{
x=-x;
y=-y;
z=-z;
}
};
int main()
{
Numbers num;
num.accept();
cout<<"\n Numbers are :\n\n";
num.display();
-num; //Overloaded Unary (-) Operator
cout<<"\n\n negated Numbers are :\n\n";
num.display();
return 0;
}

Output:

#include <iostream.h>
#include<conio.h>
class Distance
{
public:

int feet, inch;


Distance()
{
feet = 0;
inch = 0;
}

Distance(int f, int i)
{
feet = f;
inch = i;
}
Distance operator+(Distance & d2)
{
Distance d3;
d3.feet = feet + d2.feet;
d3.inch = inch + d2.inch;
return d3;
}
};
int main()
{
Distance d1(8, 9);
Distance d2(10, 2);
Distance d3;
d3 = d1 + d2;
cout << "\nTotal Feet & Inches: " << d3.feet << "'" << d3.inch;
return 0;
}

Output:
Total Feet & Inches: 18'11
Binary Operator Overloading to Subtract Complex Number

#include <iostream>
class Complex
{
private:
float real;
float imag;
public:
Complex(): real(0), imag(0)
{}
void input()
{
cout << "Enter real and imaginary parts respectively: ";
cin >> real;
cin >> imag;
}
Complex operator - (Complex c2)
{
Complex temp;
temp.real = real - c2.real;
temp.imag = imag - c2.imag;
return temp;
}
void output()
{
if(imag < 0)
cout << "Output Complex number: "<< real << imag << "i";
else
cout << "Output Complex number: " << real << "+" << imag << "i";
}
};

int main()
{
Complex c1, c2, result;

cout<<"Enter first complex number:\n";


c1.input();

cout<<"Enter second complex number:\n";


c2.input();
result = c1 - c2;
result.output();
return 0;
}

Overloading Operators on String

#include <iostream.h>
#include<conio.h>
#include<string.h>

class string
{
char str[100];
int len;

public :
void read(); // for reading string
void print(); // for printing string
// for overloading addition operator to joint two string
string operator + (string);
// for overloading equal to operator for equality of two string
int operator == (string);
};

// Function to read the string


void string :: read()
{
cout << "Enter your string : " ;
cin >> str;
len=strlen(str) ;
}
// Function to print the string
void string :: print()
{
cout << "Your string is " << str << endl ;
}
// Function definition for overloading + operator
string string :: operator+(string s)
{
string t;

strcpy(t.str,str);
strcat(t.str,s.str);

t.len = len + s.len;

return(t);
}
// Definition for equal to operator
int string :: operator == (string s)
{
if (strcmp(str,s.str)==0)
return 1 ;
else
return 0 ;
}
void main()
{
clrscr();
string s1,s2,s3;
s1.read();
s2.read();

s3 = s1 + s2 ; // call operator fucntion to join two strings.

if(s1 == s2) // call operator function to compare two strings.


cout << "Both strings are same" <<endl ;
else
cout << "Both strings are different" <<endl ;

s3.print(); // print string after joining.


getch();
}

Overloading Insertion and Extraction Operators

#include <iostream.h>
#include <conio.h>

class Box
{
double height;
double width;
double vol ;

public :
friend istream & operator >> (istream &, Box &);
friend ostream & operator << (ostream &, Box &);
};
istream & operator >> (istream &din, Box &b)
{
clrscr();
cout << "Enter Box Height: " ; din >> b.height ;
cout << "Enter Box Width : " ; din >> b.width ;
return (din) ;
}
ostream & operator << (ostream &dout, Box &b)
{
dout << endl << endl;
dout << "Box Height : " << b.height << endl ;
dout << "Box Width : " << b.width << endl ;

b.vol = b.height * b.width ;

dout << "The Volume of Box : " << b.vol << endl;
getch() ;

return(dout) ;
}

void main()
{
Box b1;

cin >> b1;


cout << b1;
}

Overloading of the subscript ([]) operator

#include<iostream.h>
#include<conio.h>
class arr
{
int a[5];
public:
arr (int *s)
{
int i;
for(i=0;i<5;i++)
a[i]=s[i];
}
int operator[] (int k)
{
return (a[k]);
}

};

int main()
{
int x[5] = {6,34,87,51,93};
arr A(x);
int i;
for (i=0;i<5;i++)
{
cout<<x[i]<<"\t";
}
getch();
return 0;
}

Output
6,34,87,51,93

Overloading of pointer to member operator


#include<iostream.h>
#include<conio.h>
class test
{
public:
int num;
test(int j)
{
num=j;
}
test *operator ->(void)
{
return this;
}
};

int main()
{
test T(5);
test *ptr = &T;
cout<<"T.num = "<<T.num;
cout<<"\n ptr->num = "<<ptr->num;
cout<<"\nT->num = "<<T->num;

getch();
return 0;
}
Inheritance

In C++, inheritance is a process in which one object acquires all the properties and
behaviors of its parent object automatically. In such way, you can reuse, extend or
modify the attributes and behaviors which are defined in other class.

Types Of Inheritance

C++ supports five types of inheritance:


1. Single inheritance
2. Multiple inheritance
3. Hierarchical inheritance
4. Multilevel inheritance
5. Hybrid inheritance

Modes of Inheritance

Public mode: If we derive a sub class from a public base class. Then the public
member of the base class will become public in the derived class and protected
members of the base class will become protected in derived class.
Protected mode: If we derive a sub class from a Protected base class. Then both
public member and protected members of the base class will become protected in
derived class.
Private mode: If we derive a sub class from a Private base class. Then both public
member and protected members of the base class will become Private in derived
class.
class A
{
public:
int x;
protected:
int y;
private:
int z;
};

class B : public A
{
// x is public
// y is protected
// z is not accessible from B
};

class C : protected A
{
// x is protected
// y is protected
// z is not accessible from C
};

class D : private A // 'private' is default for classes


{
// x is private
// y is private
// z is not accessible from D
};

Single inheritance

#include <iostream.h>
//Base class
class Parent
{
public:
int id_p;
};

// Sub class inheriting from Base Class(Parent)


class Child : public Parent
{
public:
int id_c;
};

//main function
int main()
{

Child obj1;

// An object of class child has all data members


// and member functions of class parent
obj1.id_c = 7;
obj1.id_p = 91;
cout << "Child id is " << obj1.id_c << endl;
cout << "Parent id is " << obj1.id_p << endl;

return 0;
}

Output:
Child id is 7
Parent id is 91

#include <iostream.h>
class base //single base class
{
public:
int x;
void getdata()
{
cout << "Enter the value of x = "; cin >> x;
}
};
class derive : public base //single derived class
{
private:
int y;
public:
void readdata()
{
cout << "Enter the value of y = "; cin >> y;
}
void product()
{
cout << "Product = " << x * y;
}
};

int main()
{
derive a; //object of derived class
a.getdata();
a.readdata();
a.product();
return 0;
}

Output
Enter the value of x = 3
Enter the value of y = 4
Product = 12
#include<iostream.h>
class student
{ protected:
int roll;
char name[25];
char add [25];
char city[25];
public:
student()
{
cout<<" welcome in the student information system "<<endl;
}
void getdata()
{
cout<<"\n enter the student roll no. ";
cin>>roll;
cout<<"\n enter the student name ";
cin>>name;
cout<<"\n enter ther student address ";
cin>>add;
cout<<"\n enter the student city ";
cin>>city;
}
void putdata()
{
cout<<"\n the student roll no: "<<roll;
cout<<"\n the student name: "<<name;
cout<<"\n the student city: "<<city;
}
};
class marks: public student
{
int sub1;
int sub2;
int sub3;
int per;
public:

void input()
{
getdata();
cout<<"\n enter the marks1: ";
cin>>sub1;
cout<<"\n enter the marks2: ";
cin>>sub2;
cout<<"\n enter the marks3: ";
cin>>sub3;
}
void output()
{
putdata();
cout<<"\n marks1: "<<sub1;
cout<<"\n marks2: "<<sub2;
cout<<"\n marks3: "<<sub3<<"\n";
}
void calculate ()
{
per= (sub1+sub2+sub3)/3;
cout<<"\n total percentage :: "<<per<<"\n";
}
};

int main()
{
marks m1;
int ch;
int count=0;
do
{
cout<<"\n1.input data";
cout<<"\n2.output data";
cout<<"\n3.Calculate percentage";
cout<<"\n4.exit\n";
cout<<"\nEnter the choice :: ";
cin>>ch;
switch (ch)
{
case 1:
m1.input();
count++;
break;

case 2:
m1.output();
break;

case 3:
m1.calculate();
break;
}
} while (ch!=4);
}

welcome in the student information system

1.input data
2.output data
3.Calculate percentage
4.exit

Enter the choice :: 1

enter the student roll no. 1

enter the student name Codez

enter ther student address India

enter the student city Chandigarh

enter the marks1: 80

enter the marks2: 90

enter the marks3: 70

1.input data
2.output data
3.Calculate percentage
4.exit

Enter the choice :: 2

the student roll no: 1


the student name: Codez
the student coty: Chandigarh
marks1: 80
marks2: 90
marks3: 70
1.input data
2.output data
3.Calculate percentage
4.exit

Enter the choice :: 3

total percentage :: 80

1.input data
2.output data
3.Calculate percentage
4.exit

Enter the choice :: 4

Process returned 0

Multiple Inheritance:

#include<iostream.h>
#include<conio.h>

class student
{
protected:
int rno, m1, m2;
public:
void get() {
cout << "Enter the Roll no :";
cin>>rno;
cout << "Enter the two marks :";
cin >> m1>>m2;
}
};

class sports
{
protected:
int sm; // sm = Sports mark
public:

void getsm() {
cout << "\nEnter the sports mark :";
cin>>sm;

}
};

class statement : public student, public sports


{
int tot, avg;
public:

void display() {
tot = (m1 + m2 + sm);
avg = tot / 3;
cout << "\n\n\tRoll No : " << rno << "\n\tTotal : " << tot;
cout << "\n\tAverage : " << avg;
}
};
void main()
{
clrscr();
statement obj;
obj.get();
obj.getsm();
obj.display();
getch();
}

Output
Enter the Roll no: 100

Enter two marks

90
80

Enter the Sports Mark: 90

Roll No: 100


Total : 260
Average: 86.66

#include <iostream.h>
class moving_van
{
protected:
float payload;
float gross_weight;
float mpg; //miles per gallon
public:
void initialize(float pl, float gw, float input_mpg)
{
payload = pl;
gross_weight = gw;
mpg = input_mpg;
};
float efficiency(void)
{
return (payload / (payload + gross_weight));
};
float cost_per_ton(float fuel_cost)
{
return (fuel_cost / (payload / 2000.0));
}
};
class driver
{
protected:
float hourly_pay;
public:
void initialize(float pay)
{
hourly_pay = pay;
};
float cost_per_mile(void)
{
return (hourly_pay / 55.0);
};
};
class driven_truck : public moving_van, public driver
{
public:
void initialize_all(float pl, float gw, float input_mpg, float pay)
{
payload = pl;
gross_weight = gw;
mpg = input_mpg;
hourly_pay = pay;
};
float cost_per_full_day(float cost_of_gas)
{
return ((8.0 * hourly_pay) + (8.0 * cost_of_gas * 55.0) / mpg);
};
};
int main()
{
driven_truck john_merc;
john_merc.initialize_all(20000.0, 12000.0, 5.2, 12.50);
cout<<"The efficiency of the Merc truck is "<<john_merc.efficiency()<<" %\n";
cout<<"The cost per mile for John to drive Merc
is"<<john_merc.cost_per_mile()<<"\n";
cout<<"The cost per day for John to drive Merc
is"<<john_merc.cost_per_full_day(1.129)<<"\n";
return 0;
}

#include <iostream.h>

//Base Class - basicInfo


class basicInfo
{
protected:
char name[30];
int empId;
char gender;
public:
void getBasicInfo(void)
{
cout << "Enter Name: ";
cin >> name;
cout << "Enter Emp. Id: ";
cin >> empId;
cout << "Enter Gender: ";
cin >> gender;
}
};

//Base Class - deptInfo


class deptInfo
{
protected:
char deptName[30];
char assignedWork[30];
int time2complete;
public:
void getDeptInfo(void)
{
cout << "Enter Department Name: ";
cin >> deptName;
cout << "Enter assigned work: ";
cin >> assignedWork;
cout << "Enter time in hours to complete work: ";
cin >> time2complete;
}
};

/*final class (Derived Class)- employee*/


class employee:private basicInfo, private deptInfo
{
public:
void getEmployeeInfo(void){
cout << "Enter employee's basic info: " << endl;
//call getBasicInfo() of class basicInfo
getBasicInfo(); //calling of public member function
cout << "Enter employee's department info: " << endl;
//call getDeptInfo() of class deptInfo
getDeptInfo(); //calling of public member function
}
void printEmployeeInfo(void)
{
cout << "Employee's Information is: " << endl;
cout << "Basic Information...:" << endl;
cout << "Name: " << name << endl; //accessing protected data
cout << "Employee ID: " << empId << endl; //accessing protected data
cout << "Gender: " << gender << endl << endl;//accessing protected data

cout << "Department Information...:" << endl;


cout << "Department Name: " << deptName << endl; //accessing
protected data
cout << "Assigned Work: " << assignedWork << endl; //accessing
protected data
cout << "Time to complete work: " << time2complete<< endl; //accessing
protected data
}
};

int main()
{
//create object of class employee
employee emp;

emp.getEmployeeInfo();
emp.printEmployeeInfo();

return 0;
}
Output
Enter employee's basic info:
Enter Name: Mickey
Enter Emp. Id: 1121
Enter Gender: F
Enter employee's department info:
Enter Department Name: Testing
Enter assigned work: Test Game OEM
Enter time in hours to complete work: 70
Employee's Information is:
Basic Information...:
Name: Mickey
Employee ID: 1121
Gender: F

Department Information...:
Department Name: Testing
Assigned Work: Test Game OEM
Time to complete work: 70

Multilevel Inheritance:

#include <iostream.h>
class base //single base class
{
public:
int x;
void getdata()
{
cout << "Enter value of x= "; cin >> x;
}
};
class derive1 : public base // derived class from base class
{
public:
int y;
void readdata()
{
cout << "\nEnter value of y= "; cin >> y;
}
};
class derive2 : public derive1 // derived from class derive1
{
private:
int z;
public:
void indata()
{
cout << "\nEnter value of z= "; cin >> z;
}
void product()
{
cout << "\nProduct= " << x * y * z;
}
};
int main()
{
derive2 a; //object of derived class
a.getdata();
a.readdata();
a.indata();
a.product();
return 0;
}

Output
Enter value of x= 2

Enter value of y= 3

Enter value of z= 3

Product= 18

#include<iostream>
using namespace std;
class person
{
private:
char name[15], address[15];
public:
void getdata()
{
cout<<"\nEnter Name: ";
cin>>name;
cout<<"\nEnter address: ";
cin>>address;
}
void showdata()
{
cout<<endl<<"Name: "<<name;
cout<<endl<<"Address: "<<address;
}
};
// derived class from parent class Person
class employee:public person
{
private:
int empID;
public:
void getdata()
{
person::getdata();
cout<<"\nEnter employee ID ";
cin>>empID;
}
void showdata()
{
person::showdata();
cout<<endl<<"Employee ID: "<<empID;
}
};

// derived class from parent class person


class manager: public employee
{
private:
char qual[10];
public:
void getdata()
{
employee::getdata();
cout<<"\nEnter qualification: ";
cin>>qual;
}
void showdata()
{
employee::showdata();
cout<<"\nQualification: "<<qual;
}
};

// driver program
int main()
{
manager obj;
obj.getdata();
obj.showdata();
return 0;
}

Hierarchical Inheritance:

#include <iostream.h>

class A //single base class


{
public:
int x, y;
void getdata()
{
cout << "\nEnter value of x and y:\n"; cin >> x >> y;
}
};
class B : public A //B is derived from class base
{
public:
void product()
{
cout << "\nProduct= " << x * y;
}
};
class C : public A //C is also derived from class base
{
public:
void sum()
{
cout << "\nSum= " << x + y;
}
};
int main()
{
B obj1; //object of derived class B
C obj2; //object of derived class C
obj1.getdata();
obj1.product();
obj2.getdata();
obj2.sum();
return 0;
}

Output
Enter value of x and y:
2
3
Product= 6
Enter value of x and y:
2
3
Sum= 5
#include <iostream.h>
class Number
{
private:
int num;
public:
void getNumber(void)
{
cout << "Enter an integer number: ";
cin >> num;
}
//to return num
int returnNumber(void)
{
return num;
}
};

//Base Class 1, to calculate square of a number


class Square:public Number
{
public:
int getSquare(void)
{
int num,sqr;
num=returnNumber(); //get number from class Number
sqr=num*num;
return sqr;
}
};

//Base Class 2, to calculate cube of a number


class Cube:public Number
{
private:

public:
int getCube(void)
{
int num,cube;
num=returnNumber(); //get number from class Number
cube=num*num*num;
return cube;
}
};
int main()
{
Square objS;
Cube objC;
// int sqr,cube;

objS.getNumber();
sqr =objS.getSquare();
cout << "Square of "<< objS.returnNumber() << " is: " << sqr << endl;

objC.getNumber();
cube=objC.getCube();
cout << "Cube of "<< objC.returnNumber() << " is: " << cube << endl;

return 0;
}

Output
Enter an integer number: 10
Square of 10 is: 100
Enter an integer number: 20
Cube of 20 is: 8000

Hybrid Inheritance:

#include <iostream.h>
class A
{
public:
int x;
};
class B : public A
{
public:
B() //constructor to initialize x in base class A
{
x = 10;
}
};
class C
{
public:
int y;
C() //constructor to initialize y
{
y = 4;
}
};
class D : public B, public C //D is derived from class B and class C
{
public:
void sum()
{
cout << "Sum= " << x + y;
}
};

int main()
{
D obj1; //object of derived class D
obj1.sum();
return 0;
}

Output
Sum= 14

#include<iostream>
#include<conio>
class arithmetic
{
protected:
int num1, num2;
public:
void getdata()
{
cout<<"For Addition:";
cout<<"\nEnter the first number: ";
cin>>num1;
cout<<"\nEnter the second number: ";
cin>>num2;
}
};
class plus:public arithmetic
{
protected:
int sum;
public:
void add()
{
sum=num1+num2;
}
};
class minus
{
protected:
int n1,n2,diff;
public:
void sub()
{
cout<<"\nFor Subtraction:";
cout<<"\nEnter the first number: ";
cin>>n1;
cout<<"\nEnter the second number: ";
cin>>n2;
diff=n1-n2;
}
};
class result:public plus, public minus
{
public:
void display()
{
cout<<"\nSum of "<<num1<<" and "<<num2<<"= "<<sum;
cout<<"\nDifference of "<<n1<<" and "<<n2<<"= "<<diff;
}
};
int main()
{
result z;
z.getdata();
z.add();
z.sub();
z.display();
return 0;
}

Output:
For Addition
Enter the first number:10
Enter the second number:5
For Subtraction:
Enter the first number:10
Enter the second number:5

Sum of 10 and 5= 15
Difference of 10 and 5= 5

stu sports

test

result

#include<iostream>
using namespace std;
class stu
{
protected:
int rno;
public:
void get_no(int a)
{
rno=a;
}
void put_no(void)
{
cout<<"Roll no :: "<<rno<<"\n";
}
};
class test:public stu
{
protected:
float part1,part2;
public:
void get_mark(float x,float y)
{
part1=x;
part2=y;
}
void put_marks()
{
cout<<"Marks obtained :\n"<<"part1 = "<<part1<<"\n"<<"part2 = "<<part2<<"\n";
}
};
class sports
{
protected:
float score;
public:
void getscore(float s)
{
score=s;
}
void putscore(void)
{
cout<<"Sports : "<<score<<"\n";

}
};

class result: public test, public sports


{
float total;
public:
void display(void);
};
void result::display(void)
{
total=part1+part2+score;
put_no();
put_marks();
putscore();
cout<<"Total Score = "<<total<<"\n";
}
int main()
{

result stu;
stu.get_no(123);
stu.get_mark(27.5,33.0);
stu.getscore(6.0);
stu.display();
return 0;
}

Roll no :: 123
Marks obtained :
part1 = 27.5
part2 = 33
Sports : 6
Total Score = 66.5

#include<iostream.h>
#include<conio.h>

class student
{
protected:
int roll;
public:
void get_number(int a)
{
roll= a;
}

void put_number()
{
cout<<"Roll Number: "<<roll<<endl;
}
};

class test : virtual public student


{
protected:
float part1, part2;
public:
void get_marks(float x, float y)
{
part1 = x;
part2 = y;
}

void put_marks()
{
cout<<"\nMarks Obtained: "<<endl;
cout<<"Part1 = "<<part1<<endl<<"Part2 = "<<part2<<endl;
}
};

class sports : virtual public student


{
protected:
float score;
public:
void get_score(float s)
{
score = s;
}

void put_score()
{
cout<<"\nSports Score: "<<score<<"\n\n";
}
};

class result : public test, public sports


{
private:
float total;
public:
void display()
{
total = part1 + part2 + score;
put_number();
put_marks();
put_score();
cout<<"Total Score: "<<total<<"\n";
}
};

void main()
{
clrscr();
result student;
student.get_number(83);
student.get_marks(95,98);
student.get_score(9);
student.display();
getch();
}
Pointers virtual functions and polymorphism

What are Pointers?

A pointer is a variable whose value is the address of another variable. Like any
variable or constant, you must declare a pointer before you can work with it. The
general form of a pointer variable declaration is −
type *var-name;

#include <iostream.h>
int main ()
{
int var = 20; // actual variable declaration.
int *ip; // pointer variable

ip = &var; // store address of var in pointer variable

cout << "Value of var variable: ";


cout << var << endl;

// print the address stored in ip pointer variable


cout << "Address stored in ip variable: ";
cout << ip << endl;

// access the value at the address available in pointer


cout << "Value of *ip variable: ";
cout << *ip << endl;

return 0;
}

Value of var variable: 20


Address stored in ip variable: 0xbfc601ac
Value of *ip variable: 20
#include <iostream.h>
int main() {
int *pc, c;

c = 5;
cout << "Address of c (&c): " << &c << endl;
cout << "Value of c (c): " << c << endl << endl;

pc = &c; // Pointer pc holds the memory address of variable c


cout << "Address that pointer pc holds (pc): "<< pc << endl;
cout << "Content of the address pointer pc holds (*pc): " << *pc << endl << endl;

c = 11; // The content inside memory address &c is changed from 5 to 11.
cout << "Address pointer pc holds (pc): " << pc << endl;
cout << "Content of the address pointer pc holds (*pc): " << *pc << endl << endl;

*pc = 2;
cout << "Address of c (&c): " << &c << endl;
cout << "Value of c (c): " << c << endl << endl;

return 0;
}

Output
Address of c (&c): 0x7fff5fbff80c
Value of c (c): 5

Address that pointer pc holds (pc): 0x7fff5fbff80c


Content of the address pointer pc holds (*pc): 5

Address pointer pc holds (pc): 0x7fff5fbff80c


Content of the address pointer pc holds (*pc): 11

Address of c (&c): 0x7fff5fbff80c


Value of c (c): 2

C++ Pointer to Void

These pointers can point to any type of data.


int *ptr;
double d = 9;
ptr = &d; // Error: can't assign double* to int*
However, there is an exception to this rule.
In C++, there is a general purpose pointer that can point to any type. This general
purpose pointer is pointer to void.
void *ptr; // pointer to void

Example 1: C++ Pointer to Void


#include <iostream.h>

int main()
{
void* ptr;
float f = 2.3;
ptr = &f; // float* to void

cout << &f << endl;


cout << ptr;

return 0;
}

Output
0xffd117ac
0xffd117ac

C++ Call by Reference: Using pointers


Passing by reference without pointers

#include <iostream.h>

// Function prototype
void swap(int, int);

int main()
{
int a = 1, b = 2;
cout << "Before swapping" << endl;
cout << "a = " << a << endl;
cout << "b = " << b << endl;

swap(a, b);

cout << "\nAfter swapping" << endl;


cout << "a = " << a << endl;
cout << "b = " << b << endl;

return 0;
}

void swap(int n1, int n2) {


int temp;
temp = n1;
n1 = n2;
n2 = temp;
}

Output
Before swapping
a=1
b=2

After swapping
a=2
b=1

Passing by reference using pointers

#include <iostream.h>

// Function prototype
void swap(int *, int *);

int main()
{
int a = 1, b = 2;
cout << "Before swapping" << endl;
cout << "a = " << a << endl;
cout << "b = " << b << endl;

swap(&a, &b);

cout << "\nAfter swapping" << endl;


cout << "a = " << a << endl;
cout << "b = " << b << endl;
return 0;
}

void swap(int* n1, int* n2) {


int temp;
temp = *n1;
*n1 = *n2;
*n2 = temp;
}

Pointer and arrays

#include <iostream.h>

int main () {
// an array with 5 elements.
double balance[5] = {1000.0, 2.0, 3.4, 17.0, 50.0};
double *p;

p = balance;

// output each array element's value


cout << "Array values using pointer " << endl;

for ( int i = 0; i < 5; i++ )


{
cout << "*(p + " << i << ") : ";
cout << *(p + i) << endl;
}
cout << "Array values using balance as address " << endl;

for ( int i = 0; i < 5; i++ ) {


cout << "*(balance + " << i << ") : ";
cout << *(balance + i) << endl;
}

return 0;
}

Array values using pointer


*(p + 0) : 1000
*(p + 1) : 2
*(p + 2) : 3.4
*(p + 3) : 17
*(p + 4) : 50
Array values using balance as address
*(balance + 0) : 1000
*(balance + 1) : 2
*(balance + 2) : 3.4
*(balance + 3) : 17
*(balance + 4) : 50

Pointer to object

#include <iostream.h>

class Box
{
public:
// Constructor definition
Box(double l = 2.0, double b = 2.0, double h = 2.0)
{
cout <<"Constructor called." << endl;
length = l;
breadth = b;
height = h;
}
double Volume()
{
return length * breadth * height;
}

private:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
};

int main(void) {
Box Box1(3.3, 1.2, 1.5); // Declare box1
Box Box2(8.5, 6.0, 2.0); // Declare box2
Box *ptrBox; // Declare pointer to a class.

// Save the address of first object


ptrBox = &Box1;

// Now try to access a member using member access operator


cout << "Volume of Box1: " << ptrBox->Volume() << endl;

// Save the address of second object


ptrBox = &Box2;

// Now try to access a member using member access operator


cout << "Volume of Box2: " << ptrBox->Volume() << endl;

return 0;
}

Polymorphism in C++

The word polymorphism means having many forms. In simple words, we can define
polymorphism as the ability of a message to be displayed in more than one form.
Real life example of polymorphism, a person at the same time can have different
characteristic. Like a man at the same time is a father, a husband, an employee. So
the same person possess different behavior in different situations. This is called
polymorphism.
Polymorphism is considered as one of the important features of Object Oriented
Programming.
In C++ polymorphism is mainly divided into two types:
Compile time Polymorphism

Compile time polymorphism: This type of polymorphism is achieved by


function overloading or operator overloading.

Function Overloading:
When there are multiple functions with same name but different parameters then
these functions are said to be overloaded. Functions can be overloaded by change in
number of arguments or/and change in type of arguments.
Rules of Function Overloading
// C++ program for function overloading

#include <iostream.h>
class Geeks
{
public:
// function with 1 int parameter
void func(int x)
{
cout << "value of x is " << x << endl;
}

// function with same name but 1 double parameter


void func(double x)
{
cout << "value of x is " << x << endl;
}

// function with same name and 2 int parameters


void func(int x, int y)
{
cout << "value of x and y is " << x << ", " << y << endl;
}
};

int main()
{
Geeks obj1;
obj1.func(7);
obj1.func(9.132);
obj1.func(85,64);
return 0;
}

Output:
value of x is 7
value of x is 9.132
value of x and y is 85, 64
In the above example, a single function named func acts differently in three different
situations which is the property of polymorphism.

Operator Overloading:
C++ also provide option to overload operators. For example, we can make the
operator (‘+’) for string class to concatenate two strings. We know that this is the
addition operator whose task is to add two operands. So a single operator ‘+’ when
placed between integer operands , adds them and when placed between string
operands, concatenates them.
Example:
#include<iostream.h>
class Complex
{
private:
int real, imag;
public:
Complex(int r = 0, int i =0)
{
real = r;
imag = i;
}

Complex operator + (Complex const &obj)


{
Complex res;
res.real = real + obj.real;
res.imag = imag + obj.imag;
return res;
}
void print()
{
cout << real << " + i" << imag << endl;
}
};
int main()
{
Complex c1(10, 5), c2(2, 4);
Complex c3 = c1 + c2; // An example call to "operator+"
c3.print();
return 0;
}

Output:
12 + i9

Runtime polymorphism:
This type of polymorphism is achieved by Function Overriding.

Function overriding using Virtual Function


On the other hand occurs when a derived class has a definition for one of the
member functions of the base class. That base function is said to be overridden.

Example 1: Overriding a non-virtual function


#include<iostream>
//Parent class or super class or base class
class Animal
{
public:
void animalSound()
{
cout<<"This is a generic Function";
}
};
//child class or sub class or derived class
class Dog : public Animal
{
public:
void animalSound()
{
cout<<"Woof";
}
};
int main(){
Animal *obj;
obj = new Dog();
obj->animalSound();
return 0;
}

Output:
This is a generic Function

Example 2: Using Virtual Function


#include<iostream>
//Parent class or super class or base class
class Animal
{
public:
virtual void animalSound()
{
cout<<"This is a generic Function";
}
};
//child class or sub class or derived class
class Dog : public Animal
{
public:
void animalSound(){
cout<<"Woof";
}
};
int main()
{
Animal *obj;
obj = new Dog();
obj->animalSound();
return 0;
}

Output:
Woof

#include <iostream.h>
class base
{
public:
virtual void print ()
{
cout<< "print base class" <<endl;
}

void show ()
{
cout<< "show base class" <<endl;
}
};
class derived:public base
{
public:
void print ()
//print () is already virtual function in derived class, we could also declared as virtual
void print () explicitly
{
cout<< "print derived class" <<endl;
}

void show ()
{
cout<< "show derived class" <<endl;
}
};

//main function
int main()
{
base *bptr;
derived d;
bptr = &d;

//virtual function, binded at runtime (Runtime polymorphism)


bptr->print();

// Non-virtual function, binded at compile time


bptr->show();

return 0;
}

Output:
print derived class
show base class

Difference between Function Overloading and Function overriding in C++

Function Overloading
Function overloading is a feature that allows us to have same function more than
once in a program. Overloaded functions have same name but their signature must
be different.

Function Overriding
Function overriding is a feature of OOPs Programming that allows us to override a
function of parent class in child class.

1) Function Overloading happens in the same class when we declare same functions
with different arguments in the same class. Function Overriding is happens in the
child class when child class overrides parent class function.
2) In function overloading function signature should be different for all the
overloaded functions. In function overriding the signature of both the functions
(overriding function and overridden function) should be same.
3) Overloading happens at the compile time thats why it is also known as compile
time polymorphism while overriding happens at run time which is why it is known as
run time polymorphism.
4) In function overloading we can have any number of overloaded functions. In
function overriding we can have only one overriding function in the child class.
Console Input Output Operations, Methods in C++
Console input / output function take input from standard input devices and compute
and give output to standard output device.
The standard C++ library is iostream and standard input / output functions in C++
are:

Header files available in C++ for Input/Output operations are:


1. iostream: iostream stands for standard input-output stream. This header file
contains definitions to objects like cin, cout, cerr etc.
2. iomanip: iomanip stands for input output manipulators. The methods declared
in this files are used for manipulating streams. This file contains definitions of
setw, setprecision etc.

There are mainly two types of consol I/O operations form:


Unformatted consol input output
Formatted consol input output

1) Unformatted consol input output operations


These input / output operations are in unformatted mode. The following are
operations of unformatted consol input / output operations:

A) void get()
It is a method of cin object used to input a single character from keyboard. But its
main property is that it allows wide spaces and newline character.
Example:
#include<iostream.h>
int main()
{
char c=cin.get();
cout<<c<<endl;

return 0;
}
Output
I
I

B) void put()
It is a method of cout object and it is used to print the specified character on the
screen or monitor.
Example:
#include<iostream.h>
int main()
{
char c=cin.get();
cout.put(c); //Here it prints the value of variable c;
cout.put('B'); //Here it prints the character 'c';

return 0;
}
Output
I
IB

C) getline(char *buffer, int size)


This is a method of cin object and it is used to input a string with multiple spaces.
Example:
#include<iostream.h>
int main()
{
cout<<"Enter name :";
char c[10];
cin.getline(c,10); //It takes 10 charcters as input;
cout<<c<<endl;

return 0;
}

Output
Enter name: Alphabet
Alphabet

D) write(char * buffer, int n)


It is a method of cout object. This method is used to read n character from buffer
variable.
Example:
#include<iostream.h>
int main()
{
cout<<"Enter name : ";
char c[100];
cin.getline(c,20); //It takes 20 charcters as input;
cout.write(c,20); //It reads only 20 character from buffer c;

return 0;
}
Output
Enter name : Alphabet Computers Narayangaon
Alphabet Computers Narayangaon

2) Formatted console input output operations


In formatted console input output operations we uses following functions to make
output in perfect alignment. In industrial programming all the output should be
perfectly formatted due to this reason C++ provides many function to convert any file
into perfect aligned format. These functions are available in header
file <iomanip>. iomanip refers input output manipulations.

A) width(n)
This function is used to set width of the output.
Example:
#include<iostream.h>
#include<iomanip.h>
int main()
{
int x=10;
cout<<setw(20)<<variable;

return 0;
}

Output
10

#include <iostream>
#include <iomanip>

using namespace std;

int main()
{
const int maxCount = 4;
const int width = 6;
int row;
int column;

for(row=1;row<=10;row++)
{
for(column = 1; column <= maxCount; column++)
{
cout << setw(width) << row * column;
}
cout << endl;
}

return 0;
}

Output :
1 2 3 4
2 4 6 8
3 6 9 12
4 8 12 16
5 10 15 20
6 12 18 24
7 14 21 28
8 16 24 32
9 18 27 36
10 20 30 40

B) fill(char)
This function is used to fill specified character at unused space.
Example:
#include<iostream.h>
#include<iomanip.h>
int main()
{
int x=10;
cout<<setw(20);
cout<<setfill('#')<<x;

return 0;
}

Output
##################10

D) precison(n)
This method is used for setting floating point of the output.
Example:
#include<iostream>
#include<iomanip>
int main()
{
float x=10.12345;
cout<<setprecision(5)<<x;

return 0;
}

Output
10.123

#include <iostream.h>
#include <iomanip.h>
int main (void)
{
float a,b,c;
a = 5;
b = 3;
c = a/b;
cout << setprecision (1) << c << endl;
cout << setprecision (2) << c << endl;
cout << setprecision (3) << c << endl;
cout << setprecision (4) << c << endl;
cout << setprecision (5) << c << endl;
cout << setprecision (6) << c << endl;
return 0;
}

Output:
2
1.7
1.67
1.667
1.6667
1.66667

E) setbase(arg)
This function is used to set basefield of the flag.

#include <iostream.h> // std::cout, std::endl


#include <iomanip.h> // std::setbase
int main ()
{
cout << setbase(16);
cout << 110 << endl;
return 0;
}

Output:
6e

#include <iostream.h>
int main()
{
cout << "The number 42 in octal: " << oct << 42 << '\n'
<< "The number 42 in decimal: " << dec << 42 << '\n'
<< "The number 42 in hex: " << hex << 42 << '\n';
}
Output:
The number 42 in octal: 52
The number 42 in decimal: 42
The number 42 in hex: 2a

Working with File


File Handling using File Streams in C++
File represents storage medium for storing data or information. Streams refer to sequence
of bytes. In Files we store data i.e. text or binary data permanently and use these data to
read or write in the form of input output operations by transferring bytes of data. So we use
the term File Streams/File handling. We use the header file <fstream>

 ofstream: It represents output Stream and this is used for writing in files.

 ifstream: It represents input Stream and this is used for reading from files.

 fstream: It represents both output Stream and input Stream. So it can read from files

and write to files.

Operations in File Handling:

 Creating a file: open()

 Reading data: read()

 Writing new data: write()


 Closing a file: close()

Creating/Opening a File

 We create/open a file by specifying new path of the file and mode of operation.

Operations can be reading, writing, appending and truncating.

 Syntax for file creation :

FilePointer.open("Path",ios::mode);

 Example of file opened for writing : st.open("E:\studytonight.txt",ios::out);

 Example of file opened for reading : st.open("E:\studytonight.txt",ios::in);

 Example of file opened for appending :

st.open("E:\studytonight.txt",ios::app);

 Example of file opened for truncating :

st.open("E:\studytonight.txt",ios::trunc);

Create new File


#include <iostream.h>

#include <fstream.h>

int main()

fstream file; //object of fstream class

//opening file "sample.txt" in out(write) mode

file.open("sample.txt",ios::out);

if(!file)

cout<<"Error in creating file!!!";

return 0;

cout<<"File created successfully.";

//closing the file

file.close();
return 0;

Output
File created successfully.

Writing to a File
#include <iostream.h>

#include<conio.h>

#include <fstream.h>

int main()

fstream st; // Step 1: Creating object of fstream class

st.open("studytonight.txt",ios::out); // Step 2: Creating new file

if(!st) // Step 3: Checking whether file exist

cout<<"File creation failed";

else

cout<<"New file created";

st<<"Hello"; // Step 4: Writing to file

st.close(); // Step 5: Closing file

getch();

return 0;

Here we are sending output to a file. So, we use ios::out. As given in the program,
information typed inside the quotes after "FilePointer <<" will be passed to output file.

Reading from a File


#include <iostream.h>

#include<conio.h>
#include <fstream.h>

int main()

fstream st; // step 1: Creating object of fstream class

st.open("studytonight.txt",ios::in); // Step 2: Creating new file

if(!st) // Step 3: Checking whether file exist

cout<<"No such file";

else

char ch;

while (!st.eof())

st >>ch; // Step 4: Reading from file

cout << ch; // Message Read from file

st.close(); // Step 5: Closing file

getch();

return 0;

Output
Hello
Read and Write Example

#include <fstream.h>

#include <iostream.h>

int main ()

char data[100];

// open a file in write mode.

ofstream outfile;
outfile.open("afile.dat");

cout << "Writing to the file" << endl;

cout << "Enter your name: ";

cin.getline(data, 100);

// write inputted data into the file.

outfile << data << endl;

cout << "Enter your age: ";

cin >> data;

cin.ignore();

// again write inputted data into the file.

outfile << data << endl;

// close the opened file.

outfile.close();

// open a file in read mode.

ifstream infile;

infile.open("afile.dat");

cout << "Reading from the file" << endl;

infile >> data;

// write the data at the screen.

cout << data << endl;

// again read the data from the file and display it.

infile >> data;

cout << data << endl;


// close the opened file.

infile.close();

return 0;

output −
Writing to the file
Enter your name: Zara
Enter your age: 9
Reading from the file
Zara
9

Close a File
It is done by FilePointer.close().
#include <iostream.h>

#include<conio.h>

#include <fstream.h>

int main()

fstream st; // Step 1: Creating object of fstream class

st.open("studytonight.txt",ios::out); // Step 2: Creating new file

st.close(); // Step 4: Closing file

getch();

return 0;

Special operations in a File


There are few important functions to be used with file streams like:

 tellp() - It tells the current position of the put pointer.


Syntax: filepointer.tellp()

 tellg() - It tells the current position of the get pointer.

Syntax: filepointer.tellg()

 seekp() - It moves the put pointer to mentioned location.

Syntax: filepointer.seekp(no of bytes,reference mode)

 seekg() - It moves get pointer(input) to a specified location.

Syntax: filepointer.seekg((no of bytes,reference point)

 put() - It writes a single character to file.

 get() - It reads a single character from file.

Below is a program to show importance of tellp, tellg, seekp and


seekg:

#include <iostream.h>

#include<conio.h>

#include <fstream.h>

int main()

fstream st; // Creating object of fstream class

st.open("studytonight.txt",ios::out); // Creating new file

if(!st) // Checking whether file exist

cout<<"File creation failed";

else

cout<<"New file created"<<endl;

st<<"Hello Friends"; //Writing to file


// Checking the file pointer position

cout<<"File Pointer Position is "<<st.tellp()<<endl;

st.seekp(-1, ios::cur); // Go one position back from current position

//Checking the file pointer position

cout<<"As per tellp File Pointer Position is "<<st.tellp()<<endl;

st.close(); // closing file

st.open("studytonight.txt",ios::in); // Opening file in read mode

if(!st) //Checking whether file exist

cout<<"No such file";

else

char ch;

st.seekg(5, ios::beg); // Go to position 5 from begning.

cout<<"As per tellg File Pointer Position is "<<st.tellg()<<endl; //Checking file


pointer position

cout<<endl;

st.seekg(1, ios::cur); //Go to position 1 from beginning.

cout<<"As per tellg File Pointer Position is "<<st.tellg()<<endl; //Checking file


pointer position

st.close(); //Closing file

getch();

return 0;

New file created


File Pointer Position is 13
As per tellp File Pointer Position is 12
As per tellg File Pointer Position is 5
As per tellg File Pointer Position is 6

Student database using file handling


#include<iostream.h>

#include<conio.h>

#include<stdlib.h>

#include<string.h>

#include<fstream.h>

struct student

char name[20];

char reg[15];

char course[10];

float cgpa;

};

fstream file;

student obj;

void add()

cout<<"Enter Name: ";

cin>>obj.name;

cout<<"Enter Registration Number: ";

cin>>obj.reg;

cout<<"Enter Course: ";

cin>>obj.course;

cout<<"Enter CGPA: ";

cin>>obj.cgpa;

file.open("database.txt",ios::app) ;

file.write((char*)&obj,sizeof(obj));
file.close();

void show_all()

{ // clrscr();

file.open("database.txt",ios::in);

file.read((char*)&obj,sizeof(obj));

while (file.eof()==0)

cout<<"Name: "<<obj.name<<endl;

cout<<"Registration Number: "<<obj.reg<<endl;

cout<<"Course: "<<obj.course<<endl;

cout<<"CGPA: "<<obj.cgpa<<endl<<endl;

file.read((char*)&obj,sizeof(obj));

file.close();

getch();

void search()

{ // clrscr();

float user;

cout<<"Enter CGPA: ";

cin>>user;

file.open("database.txt",ios::in);

file.read((char*)&obj,sizeof(obj));

while (file.eof()==0)

if (obj.cgpa==user)
{

cout<<"Name: "<<obj.name<<endl;

cout<<"Registration Number: "<<obj.reg<<endl;

cout<<"Course: "<<obj.course<<endl;

cout<<"CGPA: "<<obj.cgpa<<endl<<endl;

file.read((char*)&obj,sizeof(obj));

file.close();

getch();

void edit()

{ // clrscr();

char user[15];

cout<<"Enter registration Number: ";

cin>>user;

file.open("database.txt",ios::in|ios::out);

file.read((char*)&obj,sizeof(obj));

while (file.eof()==0)

if (strcmp(obj.reg,user)==0)

cout<<"Name: "<<obj.name<<endl;

cout<<"Registration Number: "<<obj.reg<<endl;

cout<<"Course: "<<obj.course<<endl;

cout<<"CGPA: "<<obj.cgpa<<endl<<endl;
cout<<"\nEnter New course: ";

cin>>obj.course;

file.seekp(file.tellg()-sizeof(obj));

file.write((char*)&obj,sizeof(obj));

cout<<"\n\nFile Updated";

break;

file.read((char*)&obj,sizeof(obj));

file.close();

getch();

void main()

// clrscr();

//file.open("database.txt",ios::out);

//file.close();

int option;

while(1)

// clrscr();

cout<<"Enter 1 to Enter Record\n";

cout<<"Enter 2 to Show All Record\n";

cout<<"Enter 3 to Search Record\n";

cout<<"enter 4 to Edit Record\n";

cout<<"Enter 5 to Exit\n";

cout<<"\n\nEnter Option: ";

cin>>option;
switch (option)

case 1:

add();

cout<<"\n\nRecord Entered\n";

getch();

break;

case 2:

show_all();

break;

case 3:

search();

break;

case 4:

edit();

break;

case 5:

exit(0);

getch();

}
#include<iostream

C++ Program to Merge Two Files into a Single file

#include<stdio.h>

#include<stdlib.h>

int main()

ifstream ifiles1, ifiles2;

ofstream ifilet;

char ch, fname1[100], fname2[100], fname3[100];

cout<<"Enter first file name :: ";

cin>>fname1;

cout<<"\nEnter second file name :: ";

cin>>fname2;

cout<<"\nEnter third name of file :: ";

cin>>fname3;
ifiles1.open(fname1);

ifiles2.open(fname2);

if(!ifiles1 || !ifiles2)

perror("\nError Message in file1111 ");

cout<<"\nPress any key to exit...\n";

exit(EXIT_FAILURE);

ifilet.open(fname3);

if(!ifilet)

perror("\nError Message ");

cout<<"\nPress any key to exit...\n";

exit(EXIT_FAILURE);

while(ifiles1.eof()==0)

ifiles1>>ch;

ifilet<<ch;

while(ifiles2.eof()==0)

ifiles2>>ch;

ifilet<<ch;
}

cout<<"\nThe two files were merged into "<<fname3<<" file successfully....!!\n";

ifiles1.close();

ifiles2.close();

ifilet.close();

return 0;

#include<iostream.h>

#include<fstream.h>

int main()

cout<<"\nText File 1 is opened........\n";

ifstream fin("file4.txt"); //opening text file

int line=1,word=1,size; //will not count first word and last line so initial value is 1

char ch;

fin.seekg(0,ios::end); //bring file pointer position to end of file

size=fin.tellg(); //count number of bytes till current postion for file pointer

fin.seekg(0,ios::beg); //bring position of file pointer to begining of file

while(fin)

fin.get(ch);

if(ch==' '||ch=='\n')

word++;
if(ch=='\n')

line++;

cout<<"\nNo. of Lines = "<<line<<"\n\nNo. of Words = "<<word;

cout<<"\n\nSize of Text File="<<size<<"\n";

fin.close(); //closing file

return 0;

Text File 1 is opened........

No. of Lines = 5

No. of Words = 32

Size of Text File=188

Templates

Templates are powerful features of C++ which allows you to write generic programs. In

simple terms, you can create a single function or a class to work with different data types

using templates.

Templates are often used in larger codebase for the purpose of code reusability and

flexibility of the programs.

The concept of templates can be used in two different ways:

Function Templates

Class Templates
Function Templates

A function template works in a similar to a normal function, with one key difference.

A single function template can work with different data types at once but, a single normal

function can only work with one set of data types.

Normally, if you need to perform identical operations on two or more types of data, you use

function overloading to create two functions with the required function declaration.

However, a better approach would be to use function templates because you can perform

the same task writing less and maintainable code.

How to declare a function template?

A function template starts with the keyword template followed by template parameter/s

inside < > which is followed by function declaration.

template <class T>

T someFunction(T arg)

... .. ...

Example 1: Function Template to find the largest number

Program to display largest among two numbers using function templates.

#include <iostream.h>

// template function

template <class T>

T Large(T n1, T n2)

return (n1 > n2) ? n1 : n2;

int main()

int i1, i2;


float f1, f2;

char c1, c2;

cout << "Enter two integers:\n";

cin >> i1 >> i2;

cout << Large(i1, i2) <<" is larger." << endl;

cout << "\nEnter two floating-point numbers:\n";

cin >> f1 >> f2;

cout << Large(f1, f2) <<" is larger." << endl;

cout << "\nEnter two characters:\n";

cin >> c1 >> c2;

cout << Large(c1, c2) << " has larger ASCII value.";

return 0;

Output

Enter two integers:

10

10 is larger.

Enter two floating-point numbers:

12.4

10.2

12.4 is larger.

Enter two characters:

Z
z has larger ASCII value.

Example 2: Swap Data Using Function Templates

Program to swap data using function templates.

#include <iostream.h>

template <class T>

void Swap(T &n1, T &n2)

T temp;

temp = n1;

n1 = n2;

n2 = temp;

int main()

int i1 = 1, i2 = 2;

float f1 = 1.1, f2 = 2.2;

char c1 = 'a', c2 = 'b';

cout << "Before passing data to function template.\n";

cout << "i1 = " << i1 << "\ni2 = " << i2;

cout << "\nf1 = " << f1 << "\nf2 = " << f2;

cout << "\nc1 = " << c1 << "\nc2 = " << c2;

Swap(i1, i2);

Swap(f1, f2);

Swap(c1, c2);

cout << "\n\nAfter passing data to function template.\n";

cout << "i1 = " << i1 << "\ni2 = " << i2;
cout << "\nf1 = " << f1 << "\nf2 = " << f2;

cout << "\nc1 = " << c1 << "\nc2 = " << c2;

return 0;

Output

Before passing data to function template.

i1 = 1

i2 = 2

f1 = 1.1

f2 = 2.2

c1 = a

c2 = b

After passing data to function template.

i1 = 2

i2 = 1

f1 = 2.2

f2 = 1.1

c1 = b

c2 = a

Class Templates

Like function templates, you can also create class templates for generic class operations.

Sometimes, you need a class implementation that is same for all classes, only the data

types used are different.

Normally, you would need to create a different class for each data type OR create different

member variables and functions within a single class.

This will unnecessarily bloat your code base and will be hard to maintain, as a change is one

class/function should be performed on all classes/functions.


However, class templates make it easy to reuse the same code for all data types.

Example 3: Simple calculator using Class template

Program to add, subtract, multiply and divide two numbers using class template

#include <iostream.h>

template <class T>

class Calculator

private:

T num1, num2;

public:

Calculator(T n1, T n2)

num1 = n1;

num2 = n2;

void displayResult()

cout << "Numbers are: " << num1 << " and " << num2 << "." << endl;

cout << "Addition is: " << add() << endl;

cout << "Subtraction is: " << subtract() << endl;

cout << "Product is: " << multiply() << endl;

cout << "Division is: " << divide() << endl;

T add() { return num1 + num2; }

T subtract() { return num1 - num2; }

T multiply() { return num1 * num2; }


T divide() { return num1 / num2; }

};

int main()

Calculator<int> intCalc(2, 1);

Calculator<float> floatCalc(2.4, 1.2);

cout << "Int results:" << endl;

intCalc.displayResult();

cout << endl << "Float results:" << endl;

floatCalc.displayResult();

return 0;

Output

Int results:

Numbers are: 2 and 1.

Addition is: 3

Subtraction is: 1

Product is: 2

Division is: 2

Float results:

Numbers are: 2.4 and 1.2.

Addition is: 3.6

Subtraction is: 1.2

Product is: 2.88

Division is: 2
#include<conio.h>

#include<iostream.h>

template<class bubble>

void bubble(bubble a[], int n)

int i, j;

for(i=0;i<n-1;i++)

for(j=i+1;j<n;j++)

if(a[i]>a[j])

bubble element;

element = a[i];

a[i] = a[j];

a[j] = element;

void main()

int a[6]={57,22,39,7,4,16};

char b[4]={'s','b','d','e'};

clrscr();

bubble(a,6);

cout<<"\nSorted Order Integers: ";

for(int i=0;i<6;i++)

cout<<a[i]<<"\t";

bubble(b,4);
cout<<"\nSorted Order Characters: ";

for(int j=0;j<4;j++)

cout<<b[j]<<"\t";

getch();

Output

Sorted Order Integers: 7 4 16 22 39 57

Sorted Order Characters: b d e s

You might also like