Strings
Put():-
a member of ostream class can be used to print a character.
Get():-
a member of istream class can be used to accept a character.
Character I/O with get() and put()
#include <iostream.h>
#include <conio.h>
void main()
{
char c;
clrscr();
cout<<"INPUT TEXT \n";
cin.get(c);
cout.put(c);
getch();
}
getline() and write() functions:-
The getline() function
It reads a whole line of text that ends with a newline character.This function can be invokedby using the object cin as follows:
Syntax:-
cin.getline(line,size);
Reading Strings With getline()
#include <iostream.h>
#include <conio.h>
void main()
{
char nm[20];
clrscr();
cout<<"Enter your name";
cin.getline(nm,20);
cout<<"Name is "<<nm;
getch();
}
The write() function
It displays an entire line and has the following form:
cout.write(line,size);
The first argument line represents the name of the string to be displayed and the second argument size indicates the number of characters automatically when the null character is encountered. If the size is greater than the length of line, then it displays beyond the bound of line.
Displaying String With write()
#include<iostream.h>
#include<conio.h>
void main()
{
char nm[20];
clrscr();
cout<<"Enter your name";
cin.getline(nm,20);
cout<<"Name is ";
cout.write(nm,7);
getch();
}

Formatted Console I/O Operations

C++ supports a number of features that could be used for formatting the output.These features include:
--ios class function and flags.
--manipulators.
--User-defined output functions.
The ios class contains a large number of member functions that would help us to format the output in a number of ways. The most importany ones among them are listed in table
ios format functions
Function Task
Width() To specify the required field size for displaying an output value
Precision() To specify the number of digits to be displayed after the decimal point of float value
Fill() To specify a character that is used to fill the unused portion of a field.
Setf() To specify format flags that can control the form of output display(such as left-justification and right-justification)
Unsetf() To clear the flags specified

ios class function and flags.
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
cout.setf(ios::left,ios::adjustfield);
cout.width(10);
cout<<"EMP NO";
cout.fill('*');
cout.width(10);
cout<<"EMP NAME";
cout.fill(' ');
cout.width(10);
cout<<"EMP SALARY";
cout<<endl;
cout.unsetf(ios::left);
cout.width(10);
cout<<100;
cout.fill('*');
cout.width(10);
cout<<"Rama";
cout.fill(' ');
cout.width(10);
cout.precision(2);
cout.setf(ios::scientific,ios::floatfield);
cout<<156.2323;
cout.width(10);
cout<<endl;
cout<<101;
cout.fill('*');
cout.width(10);
cout<<"Uma";
cout.fill(' ');
cout.width(10);
cout.precision(2);
cout.unsetf(ios::scientific);
cout<<156.2323;
getch();
}
Manipulators
These are special functions that can be included in the I/O statements to alter the format parameter of stream. To access these manipulators, the file iomanip should be included in the program.
Manipulators
Manipuators Equivalent ios function
setw() width()
setprecision() precision()
setfill() fill()
setiosflags() setf()
resetiosflags() unsetf()

Defining Field Width:width()
The width() function is used to define the width of a field necessary for the output of an item.As it is a member function object is required to invoke it like
Syntax:-
cout.width(w);
Setting Precision: precision():-
By default ,the floating numbers are printed with six digits after the decimal points. However ,we can specify the number of digits to be displayed after the decimal point while printing the floating point numbers.
This can be done by using the precision () member function as follows:
Syntax:-
cout.precision(d);
where d is the number of digits to the right of decimal point.for example the statements.
FILLING AND PADDING :fill()
The unused portion of field width are filled with white spaces, by default. The fill() function can be used to fill the unused positions by any desired character.It is used in the following form:
cout.fill(ch);
Where ch represents the character which is used for filling the unused positions.
FORMATTING FLAGS,Bit Fields and setf():-
The setf() a member function of the ios class, can provide answers left justified.The setf() function can be used as follows:
Syntax:-
cout.setf(arg1.arg2) ;
The arg1 is one of the formatting flags defined in the class ios.The formatting flag specifies the format action required for the output.Another ios constant,arg2,known as bit field specifies the group to which the formatting flag belongs.
for example:
cout.setf(ios::left,ios::adjustfield);
cout.setf(ios::scientific,ios::floatfield);
manipulators example
#include<iostream.h>
#include<conio.h>
#include<iomanip.h>
void main()
{
clrscr();
cout<<setiosflags(ios::left);
cout<<setw(10);
cout<<"EMP NO";
cout<<setfill('*');
cout<<setw(10);
cout<<"EMP NAME";
cout<<setfill(' ');
cout<<setw(10);
cout<<"EMP SALARY";
cout<<endl;
cout<<resetiosflags(ios::left);
cout<<setw(10);
cout<<100;
cout<<setfill('*');
cout<<setw(10);
cout<<"Rama";
cout<<setfill(' ');
cout<<setw(10);
cout<<setprecision(2);
cout<<setiosflags(ios::scientific);
cout<<156.2323;
cout<<setw(10);
cout<<endl;
cout<<101;
cout<<setfill('*');
cout<<setw(10);
cout<<"Uma";
cout<<setfill(' ');
cout<<setw(10);
cout<<setprecision(2);
cout<<resetiosflags(ios::scientific);
cout<<156.2323;
getch();
}

Designing our own manipulators:-

The general form for creating a manipulator without any argument is
ostream & manipulator (ostream & output)
{
……………
…………….(code)
……………..
return output;
}
User defined manipulators
#include <iostream.h>
#include <iomanip.h>
ostream ¤cy (ostream & output)
{
output<< “Rs”;
return output;
}
ostream & form (ostream &output)
{
output.set(ios::showpos);
output.setf(ios::showpoint);
output.fill(‘*’);
output.precision(2);
output<<setiosflags(ios::fixed)<<setw(10);
return output;
}
void main()
{
cout<<currency<<form<<7864.5;
}

Enumeration
An enumeration is a user-defined type whose value is restricted to one of several explicitly named constants(enumerators). Enumeration are defined using keyword: enum.
Enumeration example
#include <iostream.h>
enum seasons
{
spring,
summer,
autumn,
winter
};
void main()
{
seasons s;
s = spring;
cout << "spring = " << s << endl;
s = summer;
cout << "summer = " << s << endl;
s = autumn;
cout << "autumn = " << s << endl;
s = winter;
cout << "winter = " << s<< endl;
}

Exception Handling

Exception handling allows you to manage run-time errors in an orderly fashion. Using exception handling, your program can automatically invoke an error-handling routine when an error occurs. C++ exception handling is built upon three keywords: try, catch, and throw. program statements that you want to monitor for exceptions are contained in a try block. If an exception (i.e., an error) occurs within the try block, it is thrown (using throw). The exception is caught, using catch, and processed. Code that you want to monitor for exceptions must have been executed from within a try block. (Functions called from within a try block may also throw an exception.) Exceptions that can be thrown by the monitored code are caught by a catch statement, which immediately follows the try statement in which the exception was thrown.
The general form of try and catch are shown here.
try
{
// try block
}
catch (type1 arg)
{
// catch block
}
catch (type2 arg)
{
// catch block
}
catch (type3 arg)
{
// catch block
}...
catch (typeN arg)
{
// catch block
}

// This example will not work.
#include <iostream>
using namespace std;
void main()
{
cout << "Start\n";
try
{
cout << "Inside try block\n";
throw 100; // throw an error
cout << "This will not execute";
}
catch (double i)
{
cout << "Caught an exception -- value is: ";
cout << i << "\n";
}
cout << "End";
}

/* Throwing an exception from a function outside the try block. */
#include <iostream>
using namespace std;
void Xtest(int test)
{
cout << "Inside Xtest, test is: " << test << "\n";
if(test)
throw test;
}
void main()
{
cout << "Start\n";
try
{
cout << "Inside try block\n";
Xtest(0);
Xtest(1);
Xtest(2);
}
catch (int i)
{
cout << "Caught an exception -- value is: ";
cout << i << "\n";
}
cout << "End";
}

Catching Class Types
An exception can be of any type, including class types that you create. Actually, in real-world programs, most exceptions will be class types rather than built-in types. Perhaps the most common reason that you will want to define a class type for an exception is to create an object that describes the error that occurred. This information can be used by the exception handler to help it process the error.

// Catching class type exceptions.
#include <iostream>
#include <string>
using namespace std;
class MyException
{
public:
char str_what[80];
int what;
MyException()
{
*str_what = 0;
what = 0;
}
MyException(char *s, int e)
{
strcpy(str_what, s);
what = e;
}
};
void main()
{
int i;
try
{
cout << "Enter a positive number: ";
cin >> i;
if(i<0)
throw MyException("Not Positive", i);
}
catch (MyException e)
{
// catch an error
cout << e.str_what << ": ";
cout << e.what << "\n";
}
}

Using Multiple catch Statements
You can have more than one catch associated with a try. each catch must catch a different type of exception.

For example, this program catches both integers and strings.
#include <iostream>
using namespace std;
// Different types of exceptions can be caught.
void Xhandler(int test)
{
try
{
if(test)
throw test;
else
throw "Value is zero";
}
catch(int i)
{
cout << "Caught Exception #: " << i << '\n';
}
catch(const char *str)
{
cout << "Caught a string: ";
cout << str << '\n';
}
}
void main()
{
cout << "Start\n";
Xhandler(1);
Xhandler(2);
Xhandler(0);
Xhandler(3);
cout << "End";
}

Handling Derived-Class Exceptions
when trying to catch exception types that involve base and derived classes because a catch clause for a base class will also match any class derived from that baseThus, if you want to catch exceptions of both a base class type and a derived class type, put the derived class first in the catch sequence..

// Catching derived classes.
#include <iostream>
using namespace std;
class B
{
};
class D: public B
{
};
void main()
{
D derived;
try
{
throw derived;
}
catch(B b)
{
cout << "Caught a base class.\n";
}
catch(D d)
{
cout << "This won't execute.\n";
}
}

Catching All Exceptions
In some circumstances you will want an exception handler to catch all exceptions instead of just a certain type. This is easy to accomplish.
Simply use this form of catch.
catch(...)
{
// process all exceptions
}
// This example catches all exceptions.
#include <iostream>
using namespace std;
void Xhandler(int test)
{
try
{
if(test==0)
throw test; // throw int
if(test==1)
throw 'a'; // throw char
if(test==2)
throw 123.23; // throw double
}
catch(...)
{
// catch all exceptions cout << "Caught One!\n";
}
}
void main()
{
cout << "Start\n";
Xhandler(0);
Xhandler(1);
Xhandler(2);
cout << "End";
}

Restricting Exceptions
You can restrict the type of exceptions that a function can throw outside of itself. In fact, you can also prevent a function from throwing any exceptions whatsoever. To accomplish these restrictions, you must add a throw clause to a function definition.
The general form of this is shown here:
ret-type func-name(arg-list) throw(type-list)
{
// ...
}
// Restricting function throw types.
#include <iostream>
using namespace std;
// This function can only throw ints, chars, and doubles.
void Xhandler(int test)
throw(int, char, double)
{
if(test==0)
throw test; // throw int
if(test==1)
throw 'a'; // throw char
if(test==2)
throw 123.23; // throw double
}
void main()
{
cout << "start\n";
try
{
Xhandler(0); // also, try passing 1 and 2 to Xhandler()
}
catch(int i)
{
cout << "Caught an integer\n";
}
catch(char c)
{
cout << "Caught char\n";
}
catch(double d)
{
cout << "Caught double\n";
}
cout << "end";
}

Rethrowing an Exception
If you wish to rethrow an expression from within an exception handler, you may do so by calling throw, by itself, with no exception. This causes the current exception to be passed on to an outer try/catch sequence.
// Example of "rethrowing" an exception.
#include <iostream>
using namespace std;
void Xhandler()
{
try
{
throw "hello"; // throw a char *
}
catch(const char *)
{ // catch a char *
cout << "Caught char * inside Xhandler\n";
throw ; // rethrow char * out of function
}
}
C++ void main()
{
cout << "Start\n";
try
{
Xhandler();
}
catch(const char *)
{
cout << "Caught char * inside main\n";
}
cout << "End";
}

Applying Exception Handling
Exception handling is designed to provide a structured means by which your program can handle abnormal events. This implies that the error handler must do something rational when an error occurs. For example, consider the following simple program. It inputs two numbers and divides the first by the second. It uses exception handling to manage a divide-by-zero error.
#include <iostream>
using namespace std;
void divide(double a, double b);
void main()
{
double i, j;
do
{
cout << "Enter numerator (0 to stop): ";
cin >> i;
cout << "Enter denominator: ";
cin >> j;
divide(i, j);
}
while(i != 0);
}
void divide(double a, double b)
{
try
{
if(!b)
throw b; // check for divide-by-zero
cout << "Result: " << a/b << endl;
}
catch (double b)
{
cout << "Can't divide by zero.\n";
}
}

Templates or Generics

Templates help you achieve one of the most important goals in programming: the creation of reusable code. Through the use of template classes you can create structures that can be applied over and over again to a variety of programming situations. Generic functions and classes provide a powerful tool that you can use to expand your programming efforts. Once you have written and debugged a template class, you have a solid software component that you can use with confidence in a variety of different situations. You are saved from the dullness of creating separate implementations for each data type with which you want the class to work. Generic representation purpose we use < any letter >. That may be any character.
There are two types of templates
1. class templates (or) template classes (or) Generic Classes
2. function templates (or) template Functions (or) generic function

Generic Classes
Generic classes are useful when a class uses logic that can be generalized. When you create a generic class, it can perform the operation you define, such as maintaining a queue or a linked list, for any type of data. The compiler will automatically generate the correct type of object, based upon the type you specify when the object is created.
The general form of a generic class declaration is shown here:
template <class Ttype> class class-name
{
...
}

Once you have created a generic class, you create a specific instance of that class using the following general form:
class-name <type> ob;

Addition of two numbers using template classes.
#include<iostream.h>
#include<conio.h>
template <class T>
class addition
{
public:
T read(T n1,T n2)
{
return n1+n2;
}
};
void main()
{
clrscr();
addition a;
cout<<endl<<"The sum of two numbers is "<<a.read(10,20);
addition b;
cout<<endl<<"The sum of two floats is "<<b.read(12.3,45.3);
getch();
}

swapping of two numbers
#include<iostream.h>
#include<conio.h>
template <class G>
class swap
{
public:
G n1,n2,t;
public:
void read()
{
cout<<endl<<"Enter two values"; cin>>n1>>n2;
}
void print()
{
cout<<endl<<"Before swapping a = "<<n1<<" and b= "<<n2;
t=n1;
n1=n2;
n2=t;
cout<<endl<<"After swapping a = "<<n1<<" and b= "<<n2;
}
};
void main()
{
clrscr();
swap s;
s.read();
swap t;
t.read();
swap u;
u.read();
t.print();
s.print();
u.print();
getch();
}

Generic Function
A generic function defines a general set of operations that will be applied to various types of data. The type of data that the function will operate upon is passed to it as a parameter. a generic function, a single general procedure can be applied to a wide range of data. A generic function is created using the keyword template. A generic function (that is, a function definition preceded by a template statement) is also called a template function.
The general form of a template function definition is shown here:
template ret-type func-name(parameter list)
{
// body of function
}

//addition of two numbers using templates.
#include<iostream.h>
#include<conio.h>
template <class T>
T read(T n1,T n2)
{
return n1+n2;
}
void main()
{
clrscr();
cout<<endl<<"The sum of two numbers is "<<read(10,20);
cout<<endl<<"The sum of two floats is "<<read(12.3,45.3);
getch();
}

Swapping of two numbers using templates
#include<iostream.h>
#include<conio.h>
template <class T>
void read(T n1,T n2)
{
T t;
cout<<endl<<"Before swapping a = "<<n1<<" and b= "<<n2;
t=n1;
n1=n2;
n2=t;
cout<<endl<<"After swapping a = "<<n1<<" and b= "<<n2;
}
void main()
{
clrscr();
read(10,20);
read('a','f');
read(12.3,45.3);
getch();
}

Files

File:- The information / data stored under a specific name on a storage device, is called a file.
Stream:-It refers to a sequence of bytes.
Binary file:-It is a file that contains information in the same format as it is held in memory.

Classes for file stream operation
ofstream: Stream class to write on files
ifstream: Stream class to read from files
fstream: Stream class to both read and write from/to files.
Opening a file
OPENING FILE USING CONSTRUCTOR
ofstreamoutFile("sample.txt"); //output only
ifstreaminFile(“sample.txt”); //input only
OPENING FILE USING open()
Stream-object.open(“filename”, mode) ;
ofstreamoutFile;
outFile.open("sample.txt");
ifstreaminFile;
inFile.open("sample.txt");

File mode parameter Meaning
ios::app Append to end of file
ios::in open file for reading only
ios::out open file for writing only
ios::binary file open in binary mode

All these flags can be combined using the bitwise operator OR (|). For example, if we want to open the file example.bin in binary mode to add data we could do it by the following call to member function open(): fstream file;
file.open ("example.bin", ios::out | ios::app | ios::binary);

Closing File
outFile.close();
inFile.close();

INPUT AND OUTPUT OPERATION

put() and get() function the function put() writes a single character to the associated stream. Similarly, the function get() reads a single character form the associated stream.
example :
ch=file.get();
file.put(ch);

WAP write a character to the file.
#include<iostream.h>
#include<fstream.h>
#include<conio.h>
void main()
{
char x;
clrscr();
cout<<"Enter a character";
cin>>x;
ofstream o("sample");
o.put(x);
cout<<"Character written to the file";
getch();
}

WAP read character from the file.
#include<iostream.h>
#include<fstream.h>
#include<conio.h>
#include<process.h>
void main()
{
char x;
clrscr();
ifstream i("sample");
if(i!=NULL)
{
x=i.get();
cout<<"The Character is "<<x;
}
else
{
Cout<<"Unable to Open the file";
exit(0);
}
getch();
}

Write a program write data till you press * and print it.
#include<iostream.h>
#include<fstream.h>
#include<conio.h>
#include<process.h>
void main()
{
char x;
fstream f;
clrscr();
f.open("sssit.txt",ios::out);
cout<<"Enter data till * to exit";
do
{
x=getche();
if(x=='\n')
f.put(x);
if(x=='*')
break;
else
f.put(x);
}
while(1);
cout<<"Data written to the file";
f.close();
clrscr();
f.open("sssit.txt",ios::in);
if(f==NULL)
{
cout<<"File Doesnot Exist";
exit(0);
}
else
{
Cout<<"Data is "<<endl;
while(1)
{
x=f.get();
if(x==13)
cout<<"\n";
else if(f.eof())
break;
else
cout< }
}
getch();
}

WAP write strings to the file.
#include<iostream.h>
#include<conio.h>
void main()
{
ofstream o("sam.dat");
o<<"Countrys are "<<endl;
o<<"India"<<endl;
o<<"USA"<<endl;
o<<"UK"<<endl;
o<<"CANADA"<<endl;
o.close();
}
(or)
#include <fstream.h>
void main()
{
ofstreamfout;
fout.open("out.txt");
charstr[300] = "Time is a great teacher but unfortunately it kills all its pupils. Berlioz"; //Write string to the file.
fout< fout.close();
}

Write a Program read data from the file.
#include<fstream.h>
#include<iostream.h>
void main()
{
ifstream fin;
fin.open("sam.dat");
char ch;
while(!fin.eof())
{
ch=fin.get();
cout<<ch;
}
fin.close();
}

Write a program print no.of characters in a file.
#include<fstream.h>
#include<iostream.h>
void main()
{
ifstream fin;
fin.open("sam.dat");
int count = 0;
charch;
while(!fin.eof())
{
ch=fin.get();
count++;
}
Cout<<"Number of characters in file are "<< count;
fin.close();
}

Write a program print no.of words in a file.
#include<fstream.h>
#include<iostream.h>
#include<conio.h>
void main()
{
ifstream fin;
fin.open("sam.dat");
int count=0;
char word[20];
clrscr();
while(!fin.eof())
{
count++;
fin>> word;
}
cout<< "Number of words in file are " << count;
fin.close();
getch();
}

Write a program to print no.of lines in a program.
#include<fstream.h>
#include<iostream.h>
#include<conio.h>
void main()
{
ifstream fin;
fin.open("sam.dat");
int count = 0;
charstr[80];
clrscr();
while(!fin.eof())
{
fin.getline(str,80);
count++;
}
cout<< "Number of lines in file are " << count;
fin.close();
getch();
}

Write a program to copy one file to another.
#include<iostream.h>
#include<fstream.h>
#include<conio.h>
void main()
{
ifstream fin;
clrscr();
fin.open("sam.dat");
ofstreamfout;
fout.open("sample.txt");
char ch;
while(!fin.eof())
{
ch=fin.get();
fout<<ch;
}
fin.close();
fout.close();
getch();
}

write() and read() function write() and read() functions write and read blocks of binary data.
example:
file.read((char *)&obj, sizeof(obj));
file.write((char *)&obj, sizeof(obj));

//read and write functions example
#include<iostream.h>
#include<fstream.h> #include<stdio.h>
#include<conio.h>
class Student
{
int admno;
char name[50];
public:
void setData()
{
cout<<endl<<"Enter admission no. ";
cin >> admno;
cout<<endl<<"Enter name of student ";
cin>>name;
}
void showData()
{
cout<<endl<<"Admission no. : "<<admno;
cout<<endl<<"Student Name : "<<name;
}
int retAdmno()
{
return admno;
}
};
/* * function to write in a binary file. */
void write_record()
{
ofstream outFile;
outFile.open("xxx.dat", ios::binary | ios::app);
Student obj;
obj.setData();
outFile.write((char*)&obj, sizeof(obj));
outFile.close();
}
/* * function to display records of file */
void display()
{
ifstream inFile;
inFile.open("xxx.dat", ios::binary);
Student obj;
while(inFile.read((char*)&obj, sizeof(obj)))
{
obj.showData();
}
inFile.close();
}
/* * function to search and display from binary file */
void search(int n)
{
ifstream inFile;
inFile.open("xxx.dat", ios::binary);
Student obj;
while(inFile.read((char*)&obj, sizeof(obj)))
{
if(obj.retAdmno() == n)
{
obj.showData();
}
}
inFile.close();
}
/* * function to delete a record */
void delete_record(int n)
{
Student obj;
ifstream inFile;
inFile.open("xxx.dat", ios::binary);
ofstream outFile;
outFile.open("temp.dat", ios::out | ios::binary);
while(inFile.read((char*)&obj, sizeof(obj)))
{
if(obj.retAdmno() != n)
{
outFile.write((char*)&obj, sizeof(obj));
}
}
inFile.close();
outFile.close();
remove("xxx.dat");
rename("temp.dat", "xxx.dat");
}
/* * function to modify a record */
void modify_record(int n)
{
Student obj;
ifstream inFile;
inFile.open("xxx.dat", ios::binary);
ofstream outFile;
outFile.open("temp.dat", ios::out | ios::binary);
while(inFile.read((char*)&obj, sizeof(obj)))
{
if(obj.retAdmno() != n)
{
outFile.write((char*)&obj, sizeof(obj));
}
else
{
cout<<endl<<"Enter the new details of student";
obj.setData();
outFile.write((char*)&obj, sizeof(obj));
}
}
inFile.close();
outFile.close();
remove("xxx.dat");
rename("temp.dat", "xxx.dat");
}
void main()
{
clrscr();
//Store 4 records in file
for(int i = 1; i <= 4; i++)
write_record();
//Display all records
cout<<endl<<"List of records";
display();
//Search record
cout<<"Enter record number to display";
int rno;
cin>>rno;
search(rno);
cout<<"Enter record number to delete";
cin>>rno;
//Delete record
delete_record(rno);
cout<<"\nRecord Deleted";
display();
cout<<"Enter record number to modify";
cin>>rno;
//Modify record
cout<<endl<<"Modify Record "<<rno;
modify_record(rno);
display();
getch();
}


Object Oriented Programming Concepts ( OOPs)

Object Oriented Programming (OOP) is a programming model where programs are organized around objects and data rather than action and logic. OOP allows decomposition of a problem into a number of entities called objects and then builds data and functions around these objects.

Advantage of Object Oriented Programming

There are various advantage of using OOP over the procedural or parallel programming. Following are some of the basic advantages of using oop techniques.

1. Re-Usability of your code: If you will use OOP technique for creating your application then it will gives you a greater re-usability. For example, if you have created calculator class at one place then you can use the same calculator class in your application.
2. Easy to Maintain : Application develop using oop technique are easier to maintain than normal programming. Again let us take an example of your interest calculator class. Suppose your business need to change the calculation logic. They want to add some charges if your capital is less than 200 USD. Just think about your application is big and developed using normal programming techniques. So first you have to analyse that at how many places we have calculated interest, and then you will change. But just think of oop technique. You just need to change in your method of interest calculation at one place.
3. Good Level of Abstraction: Abstraction means making something hidden. By using oop technique you are abstracting your business logic from implementation. It will provide you greater ease. Again let us take and example of interest calculator. If you have created class for interest calculation and your team is going to use that class. Now you are only concern about how interest calculation will be performed, because you have created that. Your team member is always have understanding that if they will set rate and capital property and apply interest calculation method then it will return interest.
4. Molecularity: If we are creating separate class for your every problem then you are making it modular. So if someone need to change in the business logic part then he will always go to your business logic code part.

Class:-

A class is the core of any modern Object Oriented Programming language such as C++. A class will not occupy any memory space and hence it is only a logical representation of data. Class is a collection of data members and member functions. Data members hold the data and member functions perform the operations on the data members. To create a class, you simply use the keyword "class" followed by the class name:

Class syntax:-
Class < class-name >
{
accessspecifier:
      data members;
accessspecifier:
      memberfunctions;
};

Access specifiers (or ) Visibility modes:-

Access specifiers are used to access the data members and member functions.
There are 3 types of access specifiers
1. private:- private means within the class.
2. protected:- Protected means within the class and outside the sub classes.
3. Public:- Public means any where it is accessible.

Object:-

Oject is a runtime entity. And it is a physical representation for the class. Object is having properties. Properties are nothing but data members and member functions.

How to create a object:-
Syntax:-
class-name object;
How to access the properties:-
object.datamembers;
object.memberfunctions;

//class with data members example
#include <iostream.h >
#include < conio.h >
class sample
{
int eno;
private:
char name[10];
protected:
float sal;
public:
long int cno;
};
void main()
{
clrscr();
sample s;
//s.eno=100;
//s.name="Rama";
//s.sal=12000;
s.cno=123123123;
cout<<"Employee Contact No = "<<s.cno;
getch();
}

//class with member functions example
#include <iostream.h>
#include <conio.h>
class sample
{
public:
int print()
{
return 10;
}
void read()
{
cout <<"This is Read()";
}
};
void main()
{
clrscr();
sample s;
cout <<"The number is"<<s.print();
s.read();
getch();
}

//class with data members and member functions example
#include <iostream.h>
#include <conio.h>
class sample
{
int eno;
char name[10];
float sal;
long int cno;
public:
void read()
{
cout<<"Enter Emp No,Emp Name,salary,Contact No:";
cin>>eno>>name>>sal>>cno;
}
void print()
{
cout<<"--------------------"<<endl;
cout<<"EMPLOYEE INFORMATION"<<endl;
cout<<"EMP NO = "<<eno<<endl;
cout<<"EMP NAME = "<<name<<endl;
cout<<"EMP SALARY = "<<sal<<endl;
cout<<"EMP CONTACT NO = "<<cno<<endl;
cout<<"--------------------"<<endl;
}
};
void main()
{
clrscr();
sample s;
s.read();
s.print();
getch();
}

//class with data members and member functions example
#include <iostream.h>
#include<conio.h>
class arithmetic
{
int n1,n2;
public:
void read()
{
cout<<"Enter two numbers";
cin>>n1>>n2;
}
void add()
{
cout<<"The sum of "<<n1<<" and "<<n2<<" is "<<n1+n2<<endl;
}
void sub()
{
cout<<n1<<" - "<<n2<<" = "<<n1-n2<<endl;
}
};
void main()
{
clrscr();
arithmetic a;
a.read();
a.add();
a.sub();
getch();
}

//class with member functions
#include<iostream.h>
#include<conio.h>
class sample
{
public:
void read()
{
cout<<"This is Read()"<<endl;
}
int print()
{
return 10;
}
};
void main()
{
sample s;
clrscr();
s.read();
cout<<"The number is "<<s.print();
getch();
}

//class with data members,member functions and implement that member functions outside the class
#include<iostream.h>
#include<conio.h>
class checkevenodd
{
int n,r;
public:
void read();
void calprint();
};
void checkevenodd::read()
{
cout<<"Enter a Number";
cin>>n;
}
void checkevenodd::calprint()
{
r=n/2;
if(r*2==n)
cout<<n<<" is Even";
else
cout<<n<<" is Odd";
}
void main()
{
checkevenodd c;
clrscr();
c.read();
c.calprint();
getch();
}

//class with multiple objects
#include<iostream.h>
#include<conio.h>
class showposneg
{
int n;
public:
void read()
{
cout<<"Enter a Number";
cin>>n;
}
void calprint()
{
if(n>0)
cout<<n<<" is positive"<<endl;
else
cout<<n<<" is negative"<<endl;
}
};
void main()
{
showposneg s,s1;
clrscr();
s.read();
s.calprint();
s1.read();
s1.calprint();
getch();
}

//class with data members and member functions implement the member functions outside with using pointer object
#include<iostream.h>
#include<conio.h>
class absolute
{
int n;
public:
void read();
void calprint();
};
void absolute::read()
{
cout<<"Enter a number";
cin>>n;
}
void absolute::calprint()
{
if(n>0)
cout<<"The absolute value of "<<n<<" is "<<n;
else
cout<<"The absolute value of "<<n<<" is "<<-n;
}
void main()
{
clrscr();
absolute *a;
(*a).read(); // same a->read();
a->calprint(); //same (*a).calprint();
getch();
}

this Pointer

Every object in C++ has access to its own address through an important pointer called this pointer. The this pointer is an implicit parameter to all member functions. Therefore, inside a member function, this may be used to refer to the invoking object.

Friend functions do not have a this pointer, because friends are not members of a class. Only member functions have a this pointer.

//member function with arguments
#include<iostream.h>
#include<conio.h>
class memwithargs
{
int n1,n2;
public:
void read(int n1,int n2);
void print();
};
void memwithargs::read(int n1,int n2)
{
this->n1=n1;
this->n2=n2;
}
void memwithargs::print()
{
Cout<<"The sum is "<<n1+n2<<endl;
}
void main()
{
memwithargs m;
clrscr();
m.read(10,20);
m.print();
int n,n1;
cout<<"Enter two numbers";
cin>>n>>n1;
m.read(n,n1);
m.print();
getch();
}

//how to access private member function outside the class
#include<iostream.h>
#include<conio.h>
class memwithargs
{
int n1,n2;
void read();
public:
void print();
};
void memwithargs::read()
{
cout<<"Enter two numbers";
cin>>n1>>n2;
}
void memwithargs::print()
{
read();
cout<<"The sum is "<<n1+n2<<endl;
}
void main()
{
memwithargs m;
clrscr();
m.print();
getch();
}

Default Arguments:-

If you want to pass arguments we can pass many no. of arguments. If you want to provide default values in the implementation function we have to provide from right to left.
Syntax:- <return-type> <functionname>(variable1=value,variable2=value)
{
Statements;
}

//member function with using default arguments
#include<iostream.h>
#include<conio.h>
class memdefargs
{
public:
void simpleinterest(float pi=5000,float t=2,float r=1.50)
{
cout<<"Simple Interest = "<< (pi*t*r)/100<<endl;
cout<<"With Interest Amount = "<< (pi+(pi*t*r)/100) <<endl;
}
};
void main()
{
clrscr();
memdefargs m;
m.simpleinterest();
m.simpleinterest(6000);
m.simpleinterest(7000,1.5);
m.simpleinterest(8000,3,2);
getch();
}

ASSIGNMENTS

1. Define a class student. Read admno, sname, subject1,subject2, subject3 values and calculate total and display on the screen.
2. Define a class with batsman bcode, bname, innings, notout, runs,batavg. batavg =runs/(innings-notout)Function to compute batavg. Function to accept value from bcode, name, innings, notout. Function to display on the screen.
3.Define a class Flight with read Flight number, Destination of type, Distance of type, Fuel of type. A member function CALFUEL() to calculate the value of Fuel as per the following criteria

Distance Fuel
<=1000 500
more than 1000 and <=2000 1100
more than 2000 2200
calculate the quantity of Fuel and to allow user to view the content.

4. Define a class BOOK. Read BOOK NO, BOOKTITLE, PRICE, TOTAL_COST(). It invokes TOTAL_COST() and prints the total, cost to be paid by the user.
5. Define a class REPORT. Read admission number,name,marks, average. Function to display all data report on the screen.
5.Write the definition for a class called Rectangle that has length and width. T o calculate and return the perimeter of the rectangle.
6. Write main function to create two rectangle objects. Set the length and width of the first rectangle to 5 and 2.5. Set the length and width of the second rectangle to 5 and 18.9. Display each rectangle and its area and perimeter.
(i). Check whether the two Rectangles have the same area and print a message indicating the result. Set the length and width of the first rectangle to 15 and 6.
(ii). Display each Rectangle and its area and perimeter again. Again, check whether the two Rectangles have the same area and print a message indicating the result.
7. Write the definition for a class called complex that has floating point data members for storing real and imaginary parts. The class has the following member functions:
void set(float, float) to set the specified value in object
void disp() to display complex number object
complex sum(complex) to sum two complex numbers & return complex number
1. Write the definitions for each of the above member functions.
2. Write main function to create three complex number objects. Set the value in two objects and call sum() to calculate sum and assign it in third object. Display all complex numbers.
8. Write the definition for a class called Distance that has data member feet as integer and inches as float. The class has the following member functions:
void set(int, float) to give value to object
void disp() to display distance in feet and inches
Distance add(Distance) to sum two distances & return distance
1. Write the definitions for each of the above member functions.
2. Write main function to create three Distance objects. Set the value in two objects and call add() to calculate sum and assign it in third object. Display all distances.
9. Write the definition for a class called time that has hours and minutes as integer. The class has the following member functions:
void settime(int, int) to set the specified value in object
void showtime() to display time object
time sum(time) to sum two time object & return time
1. Write the definitions for each of the above member functions.
2. Write main function to create three time objects. Set the value in two objects and call sum() to calculate sum and assign it in third object. Display all time objects.

Encapsulation

Binding the data members and member functions into a single unit is known as Encapsulation.
Ex:- Every class with data members and member functions is a encapsulated class.
Constructor

Rules of Constructors
1. C++ constructors are the special member function of the class which are used to initialize the objects of that class
2. The constructor of class is automatically called immediately after the creation of the object.
3. Name of the constructor should be exactly same as that of name of the class.
4. Constructor should be same name as the class and declared in the public section of the class.
5. C++ constructor is called only once in a lifetime of object when object is created.
6. C++ constructors can be overloaded.
7. C++ constructors does not return any value so constructor have no return type.
8. C++ constructor does not return even void as return type.
9. Constructor can not be virtual.
10. Constructor can not be inherited, but from the derived class we can call the base class constructors.
11. It is not possible to refers to the address of constructors.
12. It is not possible to use the constructor as member of union if the object is created with constructor.

C++ Constructor Types
1. Default Constructor
2. Parametrized Constructor
3. Copy Constructor

Default Constructor 1. If the programmer does not specify the constructor in the program then compiler provides the default constructor.
2. In C++ we can overload the default compiler generated constructor
3. In both cases (user created default constructor or default constructor generated by compiler), the default constructor is always parameterless.
Syntax
class_name() {
-----
-----
}
Example of Default Constructor

//default constructor
#include<iostream.h>
#include<conio.h>
class defcon
{
public:
defcon()
{
}
};
void main()
{
clrscr();
defcon d;
getch();
}

//default constructor to print a message.
#include<iostream.h>
#include<conio.h>
class defcon
{
public:
defcon()
{
cout<<"This is Default Constructor";
}
};
void main()
{
clrscr();
defcon d;
getch();
}

//Write a program read a number and print a number with using default constructor
#include<iostream.h>
#include<conio.h>
class defcons
{
int a;
public:
defcons()
{
cout<<"Enter a Number";
cin>>a;
cout<<"The Number is "<<a;
}
};
void main()
{
clrscr();
defcons d;
getch();
}

Write a program to calculate the given year is leap year or not
#include<iostream.h>
#include<conio.h>
class defcon
{
int n;
public:
defcon()
{
cout<<"Enter Year";
cin>>n;
}
void print()
{
(n%4==0)?cout<<n<<" is Leap Year": cout<<n<<" is Not a Leap Year";
}
};
void main()
{
clrscr();
defcon d;
d.print();
getch();
}

Parameterized Constructor : class name and function name is same and it receives arguments/parameters, is called parameterized constructor.

//Write a program read employee information and print employee information.
#include<iostream.h>
#include<conio.h>
class paramet
{
public:
paramet(int empno,char ename[],float sal)
{
Cout<<"---------------------";
cout<<endl<<"EMPLOYEE INFORMATION";
cout<<endl<<"---------------------";
cout<<endl<<"EMP NO = "<<empno;
cout<<endl<<"EMP NAME = "<<ename;
cout<<endl<<"EMP SALARY = "<<sal;
cout<<endl<<"----------------------" <<endl;
}
};
void main()
{
clrscr();
paramet p(100,"Rama",12000); //implicit call
paramet p1=paramet(101,"Sneha",15500); //explicit call
int eno;
char name[10];
float sal;
cout<<"Enter employee number,name,salary";
cin>>eno>>name>>sal;
paramet p2=paramet(eno,name,sal); //explicit call
getch();
}

Copy Constructor:- A constructor that initializes an object using values of another object passed to it as parameter, is called copy constructor. It creates the copy of the passed object. There can be multiple constructors of the same class, provided they have different signatures.

//copy constructor example
#include<iostream.h>
#include<conio.h>
class copycon
{
int n;
public:
copycon()
{
cout<<"Enter a number";
cin>>n;
cout<<endl<<"Default Constructor Calling";
}
copycon(int x)
{
n=x;
cout<<endl<<"Parametrized Constructor Calling";
}
copycon(copycon &obj)
{
cout<<endl<<"Copy Constructor Calling";
n=obj.n;
}
void print()
{
cout<<endl<<"The number is "<<n;
}
};
void main()
{
clrscr();
copycon c;
c.print();
copycon c2(c);
c2.print();
copycon c1(10);
c1.print();
copycon c3(c1);
c3.print();
getch();
}<;/p>;

Wap check the given number is armstrong or not
#include<iostream.h>
#include<conio.h>
class copycon
{
int n,arm,t;
public:
copycon()
{
arm=0;
n=123;
t=n;
cout<<"The Number is "<<n<<endl;
}
copycon(int num)
{
arm=0;
t=num;
n=num;
cout<<"The Number is "<<n<<endl;
}
copycon(copycon &o);
};
copycon::copycon(copycon &o)
{
n=o.n;
while(n)
{
o.arm+=(n%10)*(n%10)*(n%10);
n/=10;
}
(o.arm==o.t)?cout<<o.t<<" is Armstrong":cout<<o.t<<" is Not Armstrong";
}
void main()
{
clrscr();
copycon c;
copycon c1(c);
int n;
cout<<"Enter a Number";
cin>>n;
copycon c2(n);
copycon c3(c2);
getch();
}

Destructor

A destructor is a special member function of a class that is executed whenever an object of it's class goes out of scope or whenever the delete expression is applied to a pointer to the object of that class.

A destructor will have exact same name as the class prefixed with a tilde (~). Destructor can be very useful for releasing resources before coming out of the program like closing files, releasing memories etc.

//destructor example
#include<iostream.h>
#include<conio.h>
class destruct
{
public:
destruct()
{
cout<<"This is Default Constructor";
}
~destruct()
{
cout<<endl<<"This is Destructor";
}
};
void main()
{
clrscr();
destruct d;
getch();
}

Inheritance
Deriving a new class from existing class is known as Inheritance.

(or)

Inheriting the base class features into derived class is known as Inheritance.

(or)

Extend the definition of a class without making any physical changes to the existing class is inheritance.

Any new class that you create from an existing class is called derived class; existing class is called base class.

Private
Private members of the base class are inaccessible to the derived class.
Protected members of the base class become private members of the derived class.
Public members of the base class become private members of the derived class.
Protected
Private members of the base class are inaccessible to the derived class.
Protected members of the base class become protected members of the derived class.
Public members of the base class become protected members of the derived class.
Public
Private members of the base class are inaccessible to the derived class.
Protected members of the base class become protected members of the derived class.
Public members of the base class become public members of the derived class.

Types of Inheritance
There are 6 types of inheritance.

Single Inheritance: It is the inheritance hierarchy wherein one derived class inherits from one base class.

//Single Inheritance
#include<iostream.h>
#include<conio.h>
class A
{
public:
void showA()
{
cout<<”This is Base Class Method”<<endl;
}
};
Class B:public A
{
public:
void showB()
{
cout<<”This is Derived Class Method”<<endl;
}
};
void main()
{
clrscr();
B b;
b.showA();
b.showB();
getch();
}

//Inheritance with Default Constructor
#include<iostream.h>
#include<conio.h>
class A
{
protected:
A()
{
cout<<”This is Base Class Constructor”<<endl;
}
};
class B
{
public:
B()
{
A::A();
Cout<<”This is Derived Class constructor”;
}
};
void main()
{
clrscr();
B b;
getch();
}

//Inheritance with Parametrized Constructor
(or)
// How to call a base class parametrized constructor in derived class
#include<iostream.h>
#include<conio.h>
class A
{
protected:
int r;
protected:
A(int a)
{
r=a/2;
}
};
Class B:private A
{
public:
B(int t):A(t)
{
((r*2)==t)?cout<<t<<” is Even”:cout<<t<<”is Odd.”<<endl;
}
};
void main()
{
clrscr();
int a;
cout<<”Enter a number”;
cin>>a;
B b(a);
getch();
}

Multi Level InheritanceBase class is inheriting features into derived class. Derived Class is inheriting features into sub derived class is nothing but Multilevel Inheritance.

//Multilevel Inheritance employee details reading and printing and calculating salary with bonus example
#include<iostream.h>
#include<conio.h>
class A
{
protected:
int eno;
char ename[10];
float sal;
};
class B:protected A
{
protected:
void read()
{
cout<<”Enter Emp no”;
cin>>eno;
cout<<”Enter Emp Name”;
cin>>ename;
cout<<”Enter Emp Salary”;
cin>>sal;
}
};
class C:protected B
{
public:
void print()
{
B::read();
cout<<”EMPLOYEE INFORMATION”<<endl;
cout<<”EMP NO = “<<eno<<endl;
cout<<”EMP NAME = “<<ename;
cout<<”EMP SALARY = “<<sal
}
};
class D:protected C
{
public:
void show()
{
C::print();
If(sal>10000)
bo=1000;
else
bo=500
cout<<”With Bonus Salary = “<<sal+bo;
}
};
void main()
{
clrscr();
D d;
d.show();
getch();
}

Hierarchial Inheritance It is the inheritance hierarchy wherein multiple subclasses inherit from one base class.

//hierarchial inheritance with reading and printing a number, calculating the square and cube of a number
#include<iostream.h>
#include<conio.h>
class Base
{
protected:
int a;
public:
void read()
{
cout<<”Enter a number”;
cin>>a;
}
};
class Derived1:public Base
{
public:
void print()
{
cout<<endl<<”The number is “<<n;
}
};
class Derived2:protected Base
{
public:
void show()
{
read();
cout<<”The square of the number is “<<n*n;
}
};
class Derived3:private Base
{
public:
void calprint()
{
base::read();
cout<<”Cube of a number is “<<n*n*n;
}
};
void main()
{
Derived1 d1;
d1.read();
d1.print();
Derived2 d2;
d2.show();
Derived3 d3;
d3.calprint();
}

Multiple Inheritance It is the inheritance hierarchy wherein one derived class inherits from multiple base class(es)

//findout the biggest number among the given numbers with using multiple inheritance
#include<iostream.h>
#include<conio.h>
class Base1
{
protected:
int n1;
};
class Base2
{
protected:
int n2;
};
class Derived:Base1,Base2
{
public:
void read()
{
cout<<”Enter two numbers”;
cin>>n1>>n2;
}
void calprint()
{
if(n1>n2)
cout<<n1<<” is Big”;
else
cout<<n2<<” is Big”;
}
};
void main()
{
clrscr();
Derived d;
d.read();
d.calprint();
}

Hybrid InheritanceSingle and Multilevel inheritance combination is nothing but hybrid inheritance.

Multipath InheritanceHierarchial and Multiple inheritance combination is nothing but Multipath Inheritance.
Virtual Base Class
Multipath inheritance may lead to duplication of inherited members from a grandparent base class (A). This may be avoided by making the common base class (A) a virtual base class. When a class is made a virtual base class(A) to B,C. C++ takes necessary care to see that only one copy of that class is inherited to D.

#include<iostream.h>
#include<conio.h>
class A
{
protected:
int n1;
};
class B:virtual public A
{
protected:
int n2;
};
class C:virtual public A
{
protected:
int n3;
};
class D:public B,public C
{
public:
void read()
{
cout<<"Enter three numbers";
cin>>n1>>n2>>n3;
}
void bigprint()
{
((n1>n2)&&(n1>n3))?cout<<n1<<" is Big":(n2>n3) ?cout<<n2<<" is Big":cout<<n3<<" is Big";
}
};
void main()
{
clrscr();
D d;
d.read();
d.bigprint();
getch();
}
Polymorphism

Polymorphism means ability to make more than form. (or) A message can be processed in different ways.
There are 2 types of polymorphism.
1. Compile Time polymorphism
2. Run Time polymorphism

Compile time polymorphism:- At the time of compiling a program it binds the data. Ex:- Operator Overloading,Function Overloading

//Unary operator overloading
#include<iostream.h>
#include<conio.h>
class sam
{
int a,b,c;
public:
sam()
{
a=10;
b=20;
c=30;
}
sam(int a,int b,int z)
{
this->a=a;
this->b=b;
c=z;
}
operator ++()
{
++a;
++b;
c++;
}
void print()
{
cout<<"The a value is "<<a<<endl;
cout<<"The b value is "<<b<<endl;
cout<<"The c value is "<<c<<endl;
}
};
void main()
{
clrscr();
sam s;
s.print();
++s;
s.print();
sam s1(99,88,77);
s1.print();
s1++;
s1.print();
getch();
}
//Binary operator overloading
#include<iostream.h>
#include<conio.h>
class sam
{
int a,b,c;
public:
sam()
{
a=10;
b=20;
c=30;
}
sam(int a,int b,int z)
{
this->a=a;
this->b=b;
c=z;
}
sam operator/(sam s)
{
sam t;
t.a=t.a/s.a;
t.b=t.b/s.b;
t.c=t.c/s.c;
return t;
}
void print()
{
cout<<"A value is "<<a<<endl<<"B value is "<<b<<endl<<"C value is "<<c;
}
};
void main()
{
clrscr();
sam o;
o.print();
sam o1(1,2,3);
o1.print();
sam o2;
o2=o/o1;
o2.print();
getch();
}
Runtime Polymorphism:- At runtime it binds the data.
Ex:- Virtual functions.
Overriding Base Class Functions
A derived class can override a member function of its base class by defining a derived class member function with the same name and parameter list. It is often useful for a derived class to define its own version of a member function inherited from its base class. This may be done to specialize the member function to the needs of the derived class. When this happens, the base class member function is said to be overridden by the derived class.
#include<iostream.h>
#include<conio.h>
class A
{
public:
void print()
{
cout<<"This is Base Class print()";
}
};
class B:public A
{
public:
void print()
{
cout<<endl<<"This is Derived Class print()";
}
};
void main()
{
clrscr();
B b;
b.print();
getch();
}
Gaining Access to an Overridden Function
It is occasionally useful to be able to call the overridden version. This is done by using the scope resolution operator to specify the class of the overridden member function being accessed.
//How to execute both base and derived class methods.
#include<iostream.h>
#include<conio.h>
class A
{
public:
void print()
{
cout<<"This is Base Class print()";
}
};
class B:public A
{
public:
void print()
{
A::print();
cout<<endl<<"This is Derived Class print()";
}
};
void main()
{
clrscr();
B b;
b.print();
getch();
}
Runtime Polymorphism:-
In C++, a pointer variable of a base class type can point to an object of its derived class. There are situations when this feature of C++ can be used to develop generic code for a variety of applications. In general, a pointer to a base class that actually points to a derived class object must first be appropriately cast before the additional features of the derived class can be used. Virtual functions are used in C++ to support polymorphic behavior.
Pointer of base class
#include<iostream.h>
#include<conio.h>
class A
{
public:
virtual void print()
{
cout<<"This is Base Class print()";
}
};
class B:public A
{
public:
void print()
{
cout<<endl<<"This is Derived Class print()";
}
};
void main()
{
clrscr();
A *a,o;
a=&o;
a->print(); //same as (*a).print();
B b;
a=&b;
(*a).print();
getch();
}
A member of a class that can be redefined in its derived classes is known as a virtual member. In order to declare a member of a class as virtual, we must precede its declaration with the keyword virtual. The member function print() has been declared as virtual in the base class because it is later redefined in each derived class. The advantage of having virtual function is that we are able to access print() function of derived class by pointer variable of base class.
Data Abstraction:- Abstraction is nothing but hiding. Hiding concept is lined up with inheritance and virtual functions.
Pure Virtual Function and Abstract Class
In above example, base class abstr member function display() do not need any implementation because it is overriding in derived class. If this is the case, the C++ language permits the programmer to declare the function a pure virtual function. The C++ way of declaring a pure virtual function is to put the expression = 0 in the class declaration. For example, if a member function double display() is being declared pure virtual, then its declaration in its class looks like
virtual double display() = 0;
A pure virtual function is sometimes called an abstract function, and a class with at least one pure virtual function is called an abstract class. The C++ compiler will not allow you to instantiate an abstract class. Abstract classes can only be subclassed: that is, you can only use them as base classes from which to derive other classes.
A class derived from an abstract class inherits all functions in the base class, and will itself be an abstract class unless it overrides all the abstract functions it inherits. The usefulness of abstract classes lies in the fact that they define an interface that will then have to be supported by objects of all classes derived from it.
#include<iostream.h>
#include<conio.h>
class abstr
{
protected:
int n;
public:
void read()
{
n=5;
}
virtual void display(){};
};
class purev:public abstr
{
public:
void display()
{
cout<<endl<<"The number is "<<n;
}
};
class purev1:public abstr
{
public:
void display()
{
cout<<endl<<"The square of a number is "<<n*n;
}
};
void main()
{
clrscr();
purev p;
p.read();
p.display();
purev1 p1;
p1.read();
p1.display();
getch();
}


Dynamic Binding:- Object binds the data dynamically at runtime.
Message Passing:- Object passes the data from one function to another.

Structure of a C++ Program

Comment section
Include files
Class Declaration
Class Function Definition
Main Function
Structure of C++ Program
Comment Section:-

Comment section contains the name of the program, author of the program etc. These comments we can provide in two types.

1.Single line comment
2.Multiline Comment

Single line Comment:- It is represented with //. If you write // before any line that line is ignored by the compiler.
Multiline Comment:- It is represented with /* and */. Within /* and */ we can write many no. of lines. Those lines ignored by the compiler.
Note:- Single line or multiline comments we use in our program many no. of times according to the purpose.

Include files:-

Include files are used to include the user defined files or header files. Source file for C++ is #include
# is a preprocessor
Include is a directive
I means input
O means output
Stream is nothing but string
H means header file.

Class Declaration:-

Class declaration contains only class <classname>; . This is used in the combination of data members and member functions and friend functions.

Class Definition:-

Class definition contains

class < classname >
{
<accessspecifier>:
<datamembers>;
<accessspecifier>:
<memberfunctions>;
};

Class Function Definition:-

We can define class functions within the class or outside the class.

main():-

Program execution starts from the main(). By default main() contains 2 arguments in c++. Those are argc,argv. Argc means argument count. Argv means argument vector list. main() contains collection of objects. Objects are used to access the data members and member functions of the class. main() is having by default return type is int. but int occupies 2 bytes space in the memory. So we use void. Because void doesn’t occupies any space in the memory.

Procedure oriented and object oriented differences
1. It follows top down approach.1. It follows bottom up approach.
2. large programs are divided into functions.2.Programs are divided into objects.
3.Most of the share global data.3. Data structures are designed such that they characterize the objects.
4. Data move openly around the system from function to function.4.Functions that operate on the data of an object are tide together in the data structure.
5.Function transform data from one form to another.5. Data is hidden and cannot be accessed by external functions.
6.Objects may communicate with each other through functions.
7.New data and functions can be easily added whenever necessary.


What is inline function

Inline functions are actual functions, which are copied everywhere during compilation, like preprocessor macro, so the overhead of function calling is reduced. All the functions defined inside class definition are by default inline, but you can also make any non-class function inline by using keyword inline with them. We must keep inline functions small, small inline functions have better efficiency. Inline functions do increase efficiency, but we should not make all the functions inline. Because if we make large functions inline, it may lead to code bloat, and might affect the speed too. Hence, it is adviced to define large functions outside the class definition using scope resolution :: operator, because if we define such functions inside class definition, then they become inline automatically.

Limitations of Inline Functions
1. Large Inline functions cause Cache misses and affect performance negatively.
2. Compilation overhead of copying the function body everywhere in the code on compilation, which is negligible for small programs, but it makes a difference in large code bases.
3. Also, if we require address of the function in program, compiler cannot perform inlining on such functions. Because for providing address to a function, compiler will have to allocate storage to it. But inline functions doesn't get storage, they are kept in Symbol table.

WAP to findout the biggest number among two numbers.

#include <iostream.h>
#include <conio.h>
class sample
{
public:
inline float calprint(double x,double y)
{
if(x>y)
return x;
else
return y;
}
};
void main()
{
clrscr();
floata,b;
cout<<"Enter two numbers";
cin>>a>>b;
sample s;
cout<<"The biggest of two numbers is "<<s.calprint(a,b);
doublep,q;
cout<<"Enter two numbers";
cin>>p>>q;
cout<<"The biggest of two numbers is "<<s.calprint(p,q);
getch();
}

PROGRAM: Calculate the product and cube of numbers
#include <iostream.h>
#include<conio.h>
class line
{
public:
inline float mul(float x,float y)
{
return(x*y);
}
inline float cube(float x)
{
return(x*x*x);
}
};
void main()
{
lineobj;
float val1,val2;
clrscr();
cout<<"Enter two values:";
cin>>val1>>val2;
cout<<"\nMultiplication value is:" <<obj.mul(val1,val2);
cout<<"\n\nCube value is :" <<obj.cube(val1) <<"\t"<<obj.cube(val2);
getch();
}

Inline function with using classes.
#include<iostream.h>
#include<conio.h>
class sample
{
public:
float calprint(double x,double y);
};
inline float sample::calprint(double x,double y)
{
if(x>y)
return x;
else
return y;
}
void main()
{
clrscr();
floata,b;
cout<<"Enter two numbers";
cin>>a>>b;
sample s;
cout<<"The biggest of two numbers is "<<s.calprint(a,b);
doublep,q;
cout<<"Enter two numbers";
cin>>p>>q;
cout<<"The biggest of two numbers is "<<s.calprint(p,q);
getch();
}