final notes cpp
final notes cpp
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.
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.
float 4bytes
double 8bytes
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.
C++ Operators
o Arithmetic Operators
o Relational Operators
o Logical Operators
o Bitwise Operators
o Assignment Operator
o Unary operator
o Ternary or Conditional Operator
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;
Output
This will give the output −
10
20
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!
#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;
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
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
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
Example
class Abc
int x;
void display()
// some statement
};
int main()
}
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, 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:
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:
int x; // Data Member Declaration
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:
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();
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;
A.rollno=1;
A.name="Adam";
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;
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
int rollno;
public:
int getRollno()
return rollno;
void setRollno(int i)
rollno=i;
};
int main()
{
Student A;
#include<iostream.h>
#include<conio.h>
class Employee
int Id;
char Name[25];
int Age;
long Salary;
public:
cin>>Id;
cin>>Name;
cin>>Age;
cout<<"\n"<<Id<<"\t"<<Name<<"\t"<<Age<<"\t"<<Salary;
};
void main()
int i;
for(i=0;i<3;i++)
E[i].GetData();
cout<<"\nDetails of Employees";
for(i=0;i<3;i++)
E[i].PutData();
Output :
Details of Employees
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
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:
// statement
};
int main()
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 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.
{
// statement
All the member functions defined inside the class definition are by default declared
as Inline.
The syntax for defining the function inline is:
// function code
#include<iostream.h>
#include<conio.h>
return s*s*s;
int main()
cout << "The cube of 3 is: " << cube(3) << "\n";
return 0;
class operation
int a,b,add,sub,mul;
float div;
public:
void get();
void sum();
void difference();
void product();
void division();
};
cin >> a;
cin >> b;
add = a+b;
cout << "Addition of two numbers: " << a+b << "\n";
sub = a-b;
cout << "Difference of two numbers: " << a-b << "\n";
mul = a*b;
cout << "Product of two numbers: " << a*b << "\n";
}
inline void operation ::division()
div=a/b;
int main()
operation s;
s.get();
s.sum();
s.difference();
s.product();
s.division();
return 0;
Output:
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.
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';
public:
};
class ABC
public:
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:
};
cout<<obj.num<<endl;
cout<<obj.ch<<endl;
int main()
XYZ obj;
disp(obj);
getch();
return 0;
Output:
100
#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 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 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
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;
}
}
}
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.
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.
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:
#include <iostream.h>
#include<conio.h>
class Example
{
int a, b;
public:
//Constructor declaration
Example();
void Display()
{
cout << "Values :" << a << "\t" << b;
}
};
int main()
{
Example Object();
cout << "Simple Constructor Outside Class Declaration Example Program In C++\n";
// Constructor invoked.
Object.Display();
getch();
return 0;
}
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:
#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;
}
7 is Prime Number.
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:
int main() {
//Normal Constructor Invoked
Example Object(10, 20);
Sample Output
Im Constructor
Im Copy Constructor
Im Copy Constructor
Values :10 20
Values :10 20
Values :10 20
Destructors in C++
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;
}
~BaseClass()
{
cout << "Destructor of the BaseClass : Object Destroyed"<<endl;
}
};
int main ()
{
BaseClass des;
getch();
return 0;
}
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];
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
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:
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;
#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);
};
strcpy(t.str,str);
strcat(t.str,s.str);
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();
#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 ;
dout << "The Volume of Box : " << b.vol << endl;
getch() ;
return(dout) ;
}
void main()
{
Box b1;
#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
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
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
};
Single inheritance
#include <iostream.h>
//Base class
class Parent
{
public:
int id_p;
};
//main function
int main()
{
Child obj1;
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);
}
1.input data
2.output data
3.Calculate percentage
4.exit
1.input data
2.output data
3.Calculate percentage
4.exit
total percentage :: 80
1.input data
2.output data
3.Calculate percentage
4.exit
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;
}
};
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
90
80
#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>
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;
}
};
// driver program
int main()
{
manager obj;
obj.getdata();
obj.showdata();
return 0;
}
Hierarchical Inheritance:
#include <iostream.h>
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;
}
};
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";
}
};
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;
}
};
void put_marks()
{
cout<<"\nMarks Obtained: "<<endl;
cout<<"Part1 = "<<part1<<endl<<"Part2 = "<<part2<<endl;
}
};
void put_score()
{
cout<<"\nSports Score: "<<score<<"\n\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
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
return 0;
}
c = 5;
cout << "Address of c (&c): " << &c << endl;
cout << "Value of c (c): " << c << 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
int main()
{
void* ptr;
float f = 2.3;
ptr = &f; // float* to void
return 0;
}
Output
0xffd117ac
0xffd117ac
#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);
return 0;
}
Output
Before swapping
a=1
b=2
After swapping
a=2
b=1
#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);
#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;
return 0;
}
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.
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
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;
}
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;
}
Output:
12 + i9
Runtime polymorphism:
This type of polymorphism is achieved by Function Overriding.
Output:
This is a generic Function
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;
return 0;
}
Output:
print derived class
show base class
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:
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
return 0;
}
Output
Enter name: Alphabet
Alphabet
return 0;
}
Output
Enter name : Alphabet Computers Narayangaon
Alphabet Computers Narayangaon
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>
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.
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
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
Creating/Opening a File
We create/open a file by specifying new path of the file and mode of operation.
FilePointer.open("Path",ios::mode);
st.open("E:\studytonight.txt",ios::app);
st.open("E:\studytonight.txt",ios::trunc);
#include <fstream.h>
int main()
file.open("sample.txt",ios::out);
if(!file)
return 0;
file.close();
return 0;
Output
File created successfully.
Writing to a File
#include <iostream.h>
#include<conio.h>
#include <fstream.h>
int main()
else
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.
#include<conio.h>
#include <fstream.h>
int main()
else
char ch;
while (!st.eof())
getch();
return 0;
Output
Hello
Read and Write Example
#include <fstream.h>
#include <iostream.h>
int main ()
char data[100];
ofstream outfile;
outfile.open("afile.dat");
cin.getline(data, 100);
cin.ignore();
outfile.close();
ifstream infile;
infile.open("afile.dat");
// again read the data from the file and display it.
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()
getch();
return 0;
Syntax: filepointer.tellg()
#include <iostream.h>
#include<conio.h>
#include <fstream.h>
int main()
else
else
char ch;
cout<<endl;
getch();
return 0;
#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()
cin>>obj.name;
cin>>obj.reg;
cin>>obj.course;
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<<"Course: "<<obj.course<<endl;
cout<<"CGPA: "<<obj.cgpa<<endl<<endl;
file.read((char*)&obj,sizeof(obj));
file.close();
getch();
void search()
{ // clrscr();
float user;
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<<"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];
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<<"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 5 to Exit\n";
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
#include<stdio.h>
#include<stdlib.h>
int main()
ofstream ifilet;
cin>>fname1;
cin>>fname2;
cin>>fname3;
ifiles1.open(fname1);
ifiles2.open(fname2);
if(!ifiles1 || !ifiles2)
exit(EXIT_FAILURE);
ifilet.open(fname3);
if(!ifilet)
exit(EXIT_FAILURE);
while(ifiles1.eof()==0)
ifiles1>>ch;
ifilet<<ch;
while(ifiles2.eof()==0)
ifiles2>>ch;
ifilet<<ch;
}
ifiles1.close();
ifiles2.close();
ifilet.close();
return 0;
#include<iostream.h>
#include<fstream.h>
int main()
int line=1,word=1,size; //will not count first word and last line so initial value is 1
char ch;
size=fin.tellg(); //count number of bytes till current postion for file pointer
while(fin)
fin.get(ch);
if(ch==' '||ch=='\n')
word++;
if(ch=='\n')
line++;
return 0;
No. of Lines = 5
No. of Words = 32
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
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
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
A function template starts with the keyword template followed by template parameter/s
T someFunction(T arg)
... .. ...
#include <iostream.h>
// template function
int main()
cout << Large(c1, c2) << " has larger ASCII value.";
return 0;
Output
10
10 is larger.
12.4
10.2
12.4 is larger.
Z
z has larger ASCII value.
#include <iostream.h>
T temp;
temp = n1;
n1 = n2;
n2 = temp;
int main()
int i1 = 1, i2 = 2;
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 << "i1 = " << i1 << "\ni2 = " << i2;
cout << "\nf1 = " << f1 << "\nf2 = " << f2;
cout << "\nc1 = " << c1 << "\nc2 = " << c2;
return 0;
Output
i1 = 1
i2 = 2
f1 = 1.1
f2 = 2.2
c1 = a
c2 = b
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
Normally, you would need to create a different class for each data type OR create different
This will unnecessarily bloat your code base and will be hard to maintain, as a change is one
Program to add, subtract, multiply and divide two numbers using class template
#include <iostream.h>
class Calculator
private:
T num1, num2;
public:
num1 = n1;
num2 = n2;
void displayResult()
cout << "Numbers are: " << num1 << " and " << num2 << "." << endl;
};
int main()
intCalc.displayResult();
floatCalc.displayResult();
return 0;
Output
Int results:
Addition is: 3
Subtraction is: 1
Product is: 2
Division is: 2
Float results:
Division is: 2
#include<conio.h>
#include<iostream.h>
template<class bubble>
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);
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