C++.pps
C++.pps
7. Class & Objects, Constructor & Destructor 14. Linked List using C++
INTRODUCTION TO POP
1.Software technology has evolved through a series of
phases the last five decades. The most popular phase
till recently was Procedure Oriented Programming
(POP).
2.POP employs top – down programming approach
where a problem is viewed as a sequence of tasks to be
performed. The numbers of functions are written to
implement these tasks.
3.The conventional programming using high level
languages such as COBOL, FORTRON and C are
commonly known as procedure oriented programming
(POP).
Drawbacks of POP
1.There are two major drawbacks in POP technology.
2.Data move freely around the program and are
therefore vulnerable to changes caused by any
function in the program.
3.It does not model very well the real world problems.
OOP (Object Oriented Programming)
Data Data
Functions Functions
Data
Functions
Object C
Some of the striking features of OOPs are
1.Emphasis is an data rather than procedure.
2.Programs are divided into what are known as objects.
3.Data structures are designed such that they characterize
the objects.
4.Functions that operate on the data of an object are tied
together in the data structure.
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.
8.Follows Bottom – Up approach is program design.
BASIC CONCEPTS OF OOPS
Data Abstraction
1.Data abstraction refers to putting together essential
features without including background details.
Data Encapsulation
1.The wrapping up of data and functions into a single
unit (called class) is known as Encapsulation.
2.The Encapsulated data is not accessible to the outside
world, and only those functions which are wrapped in
the class can access it.
Inheritance
Draw ()
Message Passing
1.Compilation : Alt+F9
2.Run: Ctrl+F9 Run
3.Result: Alt+F5
Structure of C++ Program
C++ program can be viewed as a group of building
blocks called functions.
Link Section
It links the instruction to the compiler from the system
library
Ex
#include<iostream.h>
#include<conio.h>
void main()
Every C++ program must have one void main()
function
There is at least one statement in executable part
This two parts must appear between the opening
brace and ends at the closing brace
All statements must end with semicolon(;)
Steps in Learning ‘C++’
Instructions
Program
Character Set
Alphabets a to z and A to Z
Digits 0 to 9
Special Characters ~,!,@,#,$,%.....etc.,
Variables
A variable is a data name that may be used to store a
data value
A variable may take different values at different times
during execution
Rules for Variable Name
1.It must begin with letter
2.It may a combination of letter, numeric, and
underscore(_)
3.It may be in uppercase or lowercase
4.No commas or blank spaces
5.It should not be a keyword
6.Ex: sum,avg,m1,mark1,sim_int,etc
Identifiers
Identifier refer to the names of variables, functions,
and arrays
They are user- defined name may be in lower or
upper case
Constants
They can be fixed values. Do not change during program
execution
Two types of constant
1.Numeric constant
2.Character constant
1.Numeric constant
1.Integer constant Ex: 4, 78, -100
2.Real constant Ex: 87.878,-78.567
2. Character constant
3.Single character constant Ex: ‘p’, ‘o’
4.String constant Ex: “Salem”
Keywords
1.Keywords are the words whose meaning has already
been explained to the ‘C++’ Compiler
2.Keywords are also called reserved words
3.All keywords have fixed meaning
4.All keywords must be written in lowercase
There are 32 keywords
auto double if static
break else int struct
case enum long switch
char float near union
const float register typedef
continue sizeof return unsigned
default for short void
do goto signed while
C++ Instructions
There are basically four types of instructions
1.Type declaration Instruction
2.Input/Output Instruction
3.Arithmetic Instruction
4.Control Instruction
Examples
1.Type declaration Instruction
Any variable used in the program should be declared before
using it in any statement
It should be written in beginning of C Program
Ex: int no;
float avg;
char name,code;
2. Input/Output Instruction
It is used to supply inputs data to a program
It is used to print out the results
Ex:
cout<<“Hai”; output
cin>>a>>b; Input
3. Arithmetic instruction
Ex
sum=sum+I;
tot=m1+m2+m3;
4. Control Instruction
There are four types of control instruction
1.Sequence control instruction – ex: goto
2.Decision control instruction – ex: if
3.Reputation or loop instruction – ex: for, while
4.Case control instruction – ex: switch
Data Types
‘C’ language is rich in its data types and it is represent the
type of value stored into variable.
Three data types are
1.Primary or Basic Data Type
2.User Defined Data Type [Structure]
3.Derived Data Type [Arrays and Pointers]
1. endl
The endl manipulator, when used in output
statement, causes a linefeed to be inserted. It has
the same effect as using the new line character.
Example: cout<<”m=10”<<endl<<”n=20”;
2. setw()
The setw() manipulator set the width of the output field.
Format: setw(int)
Example: cout<<”a”<<setw(5)<<”b”;
output: a b
3. setprecision()
The manipulator control the display of number of digits
after the decimal point for the floating numbers.
Format: setprecision(int)
Example: float a=88.99899;
cout<<setprecision(2)<<a;
output: 88.99
4. setfill()
This manipulator fills the given character in the unused
field.
Format: setfill(‘char’)
Example: cout<<setw(10)<<setfill(‘*’)<<“a”;
Output: *********Aqqww```
#include<iostream.h>
#include<conio.h>
#include<iomanip.h>
void main()
{
float i,j;
clrscr();
cout<<"\n\tEnter Two Numbers :"<<endl;
cin>>i>>j;
cout<<i<<"\t"<<j;
float k;
k=i/j;
cout<<"\n\tDiv is :"<<setprecision(3)<<k;
cout<<"\n\t"<<setfill('*')<<setw(10)<<k;
getch();
} Run
Operators
The operator can be defined into a number of categories.
They are
1.Arithmetic operator
2.Increment/Decrement operator
3.Relational operator
4.Logical operator
5.Assignment operator
6.Conditional operator
7.Bitwise operator
8.Special operator
1. Arithmetic Operators
- Subtraction, also unary minus
+ Addition
* Multiplication
/ Division
% Modulus
Run
#include<iostream.h>
#include<conio.h>
void main()
{
int i,j,k;
clrscr();
cout<<"\n\tEnter a Number :\n";
cin>>j;
k=j;
i=j++; /* i=j,j=j+1 */
cout<<"\n\tI Status is :"<<i;
i=++k; /* k=k+1,i=k */
cout<<"\n\tI Status is :"<<i;
getch();
} Run
Run
#include<iostream.h>
#include<conio.h>
void main()
{
int i,j,k;
clrscr();
cout<<"\n\tEnter a Number :\n";
cin>>j;
k=j;
i=j--; /* j=j,j=j-1 */
cout<<"\n\tJ Status is :"<<j;
i=--k;
cout<<"\n\tK Status is :"<<k;
getch();
}
3. Relational Operators
> Greater than
>= Greater than or equal
< Less than
<= Less than or equal
== Equal
!= Not equal
4. Logical Operators
&& AND
|| OR
! NOT
5. Assignment Operators
= Assign
-= Subtraction and Assign
+= Addition and Assign
*= Multiplication and Assign
/= Division and Assign
%= Modulus and Assign
6. The ? Operator
Exp1 ? Exp2 : Exp3;
The ? operator works like this: Exp1 is evaluated. If it is true,
Exp2 is evaluated and becomes the value of the expression. If
Exp1 is false, Exp3 is evaluated and its value becomes the
value of the expression.
Example : y = x>9 ? 100 : 200;
#include<iostream.h>
#include<conio.h>
void main()
{
int i=1,j;
clrscr();
cout<<"\n\tEnter a Number :";
cin>>j;
i+=i; /* i=i+i */
i+=j; /* i=i+j */
j/=2; /* j=j/2 */
cout<<"\n\tI is : "<<i;
cout<<"\n\tJ is : "<<j;
getch(); Run
}
7. Bitwise Operators
& AND
| OR
^ Exclusive OR (XOR)
~ One's complement (NOT)
>> Shift right
<< Shift left
8. Special Operators
#, @, “,”,’,`,…. etc.
Decision Making
Decision making statements are used to change or alter
the normal flow of a program
1.if statement
2.switch statement
3.conditional statement
4.goto statement
Looping Statements
A set of statements can be executed repeatedly until
some specific condition is satisfied. This is known as loop
C++ language provides 3 loop
1.while loop
2.do-while loop
3.for loop
ifIf statement
Statement may be implemented in different forms depending on
the complexity of conditions to be tested.
Syntax: Example:
if (Test Condition) if (i>j)
{ {
True Block k=i-j;
} }
if…..else Statement
Example:
Syntax: if (a>b)
if (Test Condition)
{ {
True Block k=a-b;
} }
else
{ else
False Block {
}
k=b-a;
}
#include<iostream.h>
#include<conio.h>
void main()
{
int i,j;
clrscr();
cout<<"\n\tEnter First Number :\n";
cin>>i;
cout<<"\n\tEnter Second Number :\n";
cin>>j;
if(i>j)
{
cout<<"\n\tI is Big";
}
else
{
cout<<"\n\tJ is Big";
}
cout<<"\n\tEnd Of Program";
getch(); Run
}
Example:
Nested If Statement if (a>b)
{
if (a>c)
{
cout<<“A is Big”;
Syntax: }
if (Test Condition) else
{ {
if (Test Condition) cout<<“C is Big”;
{ }
True Block }
else if(b>c)
} {
else cout<<“B is Big”;
{ }
False Block Else
} {
} cout<<“C is Big”;
}
#include<iostream.h>
#include<conio.h>
void main()
{
int i;
clrscr();
cout<<"\n\tEnter a Number :\n";
cin>>i;
if(i>0)
{
if(i==2)
{
cout<<"\n\t U'r Correct";
}
else
{
cout<<"\n\tWrong Number";
}
}
else
{
cout<<"\n\tNot a Possitive"; Run
}
getch();
}
else if
Syntax:
ladder
if (codition-1)
{
True Block-1 Example:
} if (avgas>60)
else if (codition-2) {
{ cout<<“A”;
True Block-2 }
} else if (avgas>40)
else if (condition-n) {
{ cout<<“B”;
True Block-n }
} else
Else {
{ cout<<“C”;
False Block }
}
Switch Statement
It is an alternative for else-if ladder.
It test the value of a given variable against a list of
case values and where match is found, block of
statement is executed.
Syntax:
switch (exp)
{ Example:
case val-1: switch (a)
Block-1; break; case {
val-2: case 1:
Block-2; cout<<“One”; break;
break; case 2:
case val-n: cout<<“Two”; break;
Block-n; default:
break; cout<<“None”;
default: }
Default Block;
}
#include<iostream.h>
#include<conio.h>
void main()
{
int i;
clrscr();
cout<<"\n\tEnter a Number :\n";
cin>>i;
switch(i)
{
case 100:
cout<<"\n\t You also got centum sasidha ";
break;
case 50:
cout<<"\n\t You score half percentage";
break;
default:
cout<<"\n\tSelect any of the choice";
}
cout<<"\n\tEnd";
getch(); Run
}
Conditional Operator
If (num>40)
i=i+4;
Else (OR)
i=i+10; i=(num>40)?i+4:i-10
#include<iostream.h>
#include<conio.h>
void main()
{
int i,j,k;
clrscr();
cout<<"\n\tEnter Two Numbers :\n";
cin>>i>>j;
k=(i>j)?i:j;
cout<<"\n\tBig Number :"<<k;
getch();
}
Run
Goto Statement
1.Goto statement to branch unconditionally form one point
to another in the program
2.Label is a valid identifier to be followed by a colon.
Example:
label:
cout<<“\n\t The goto state worked out”;
if (nu==100)
goto label;
i=i+1;
cout<<i;
getch();
#include<iostream.h>
#include<conio.h>
void main()
{
int i;
clrscr();
jos:
cout<<"\n\tEnter a Number :\n";
cin>>i;
if(i<0)
{
goto jos;
}
cout<<"\n\t Thanking U";
cout<<"\n\tEnd";
getch(); Run
}
Break Statement
The break statement is used to exit out of the loop
without checking any condition
Example:
for (i=1;i<10;i++)
{
if(i==5)
break;
}
Continue Statement
If the continue statement is executed then the revoid
maining stat of the loop is ignored and the control will go
to the beginning of the loop
Example:
for(i=1;i<10;i++)
{
If(i==5)
{
cout<<“Five”;
}
continue;
}
While loop
1.If the condition is true, the loop is executed
2.The statements are executed and the loop is
incremented
3.The loop continues to work until the condition becomes
false
Syntax: Example:
while (test condition) Int i=0,j=5,k=0;
{ while (i<=j)
body of the loop; {
increment part; k=k+I;
} i++;
}
#include<iostream.h>
#include<conio.h>
void main()
{
int i,j=0,k=0;
clrscr();
cout<<"\n\tEnter a Number :\n";
cin>>i;
while(j<i)
{
k=k+j;
cout<<"\n\t K value is:"<<k;
j++;
}
cout<<"\n\tSum of "<<i<<" Numbers is : "<<k;
getch();
} Run
Do While loop
In the do-while loop the body of the loop is executed at
least once and checks the condition
Syntax: Example:
do Int k;
{ do
body of the loop; {
}while(test_condition); cout<<“Press any Key”;
cin>>k;
}while(k!=1);
#include<iostream.h>
#include<conio.h>
void main()
{
int i;
clrscr();
do
{
cout<<"\n\tPress any Number :";
cin>>i;
}while(i!=1);
cout<<"\n\t Thank U";
getch();
}
Run
For looping
1.It is the more concise loop control structure
2.First, the initial part is executed
3.Then the body of the statement is executed.
4.Then the increment part is executed.
5.This process repeated until the test condition is true.
Syntax
for (initialization; test condition; increment/decrement)
{
body of the loop;
}
void main()
{
int i,j;
double f=1;
clrscr();
cout<<"\n\tEnter a Number :\n";
cin>>i;
for(j=1;j<=i;j++)
{
f=f*j;
}
cout<<"\n\tFact is :“<<f;
getch();
Run
}
Home
Additional features
More than one value in For Loop
can be initialized
for(p=1,i=0;i<10;i++)
More than one increment section is also allowed
for(n=1,m=50;n<=20;n=n-1,m=m+1)
Test condition may have any compound relation
sum=0
for(i=1;i<20 && sum<200;i++)
{
sum=sum+i;
}
Initial condition is omitted it should be initialize first
for(;c<=20;c++)
Test condition should not be omitted
Increment is omitted, it should be done in the body of the loop.
Array
Group of same type of values stored in a single
variable is called Array variable.
Array Types
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{
cout<<"\n\tEnter a Number :\n“;
cin>>a[i][j];
}
}
cout<<"\n\tResult \n";
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{
cout<<a[i][j];
}
cout<<endl;
}
getch();
}
Run
Home
Pointer
A pointer is nothing but a variable that contains the
address of another variable.
Consider an example
int intvar=10;
Here, intvar is the name of a variable that store the value
10, and it stored in memory in the address, say 108. This
could be represented as
108 --> the address of the variable
10 --> the variable intvar
Memory
Address Value
106
108 10
110
Pointer Variable
Pointers are variables that contain addresses. Suppose v is
a variable that represents some particular data item.The
address of v's memory location can be determined by the
expression &v, where & is a address operator. The address
of v is assigned to another variable PV as follows:PV=&v
void main()
{ myfunction()
myfunction(); {
……. statements;
} }
Pre Defined Function
Derived Function
void main()
{
clrscr();
printf("\n\tThis is void main Program");
dog(); /* Calling Function */
getch();
}
void mycsc(char n[])
{
cout<<n<<“ DYING COMPANY";
}
void main()
{
clrscr();
myaddress("SRI");
getch();
}
Run
int dog()
{
return(56+7);
}
void main()
{
int s;
clrscr();
s=dog();
cout<<"\n\t Value is :“<<s;
getch();
}
Run
int sqr(int i)
{
int g;
g=i*i;
return(g);
}
void main()
{
int h,k;
clrscr();
printf("\n\tEnter a Number :");
scanf("%d",&h);
k=sqr(h);
printf("\n\tSqr is : %d",k);
getch(); Run
}
Home
#include<iostream.h>
#include<conio.h>
int sqr()
{
return(100);
}
int sqr(int a)
{
return(a*a);
}
int sqr(int a,int b)
{
return(a*b);
} Run
void main()
{
int a,b;
clrscr();
cout<<"\n\n\n\tEnter Two Numbers:"<<endl;
cin>>a>>b;
cout<<"Ans1:"<<sqr()<<endl;
cout<<"Ans2:"<<sqr(a)<<endl;
cout<<"Ans3:"<<sqr(a,b)<<endl;
getch();
}
Run
#include<iostream.h>
#include<conio.h>
int sqr(float a,int b)
{
return((int)a+b);
}
float sqr(int a,float b)
{
return((float)a+b);
}
void main()
{
clrscr();
cout<<"Ans1:"<<sqr(2.3,2)<<endl;
cout<<"Ans2:"<<sqr(3,3.5)<<endl;
getch(); Run
}
Default Arguments
#include<iostream.h>
#include<conio.h>
class polygon
{
int *x;
int *y;
int ver;
public:
polygon(int no=2)
{
x=new int[no];
y=new int[no];
ver=no;
}
~polygon()
{
cout<<"Deleted Object";
}
void getdata()
{
for(int i=0;i<ver;i++)
{
cout<<"Enter x co-ordinate";
cin>>x[i];
cout<<"Enter y co-ordinate";
cin>>y[i];
}
}
void putdata()
{
cout<<"Vertex details "<<endl;
for(int i=0;i<ver;i++)
{
cout<<"X co-ordinate "<<x[i]<<"\t";
cout<<"Y co-ordinate "<<y[i]<<endl;
}
}
};
void main()
{
clrscr();
polygon p1(4);
p1.getdata();
p1.putdata();
}
Run
Class and Object
A class declaration defines new type that links code and data.
This new type is then used to declare objects of that class.
Thus, class is logical abstraction, but an object has physical
existence. In other words, an object is an instance of class. A
class declaration is similar syntactically to structure.
class class_name
{
Class Members
};
public
private
protected
By default, functions and data declared within class are
private to that class and may be accessed only by other
members of the class.
The public access specifier allows functions or data to be
accessible to other parts of your program.
The protected access specifier is needed only when
inheritance is involved
#include<iostream.h>
#include<conio.h>
class std
{
public:
int rno;
char name[20];
};
void main()
{
std s1;
clrscr();
cout<<"\n\tEnter Roll No and Name :";
cin>>s1.rno>>s1.name;
cout<<"\n\tRoll No :"<<s1.rno;
cout<<"\n\tName :"<<s1.name; Run
getch();
}
#include<iostream.h>
#include<conio.h>
class std
{
private:
int rno;
char name[20];
public:
void read()
{
cout<<"\n\tEnter Roll No and Name :"<<endl;
cin>>rno>>name;
}
void print()
{
cout<<"\n\tRoll No :"<<rno;
cout<<"\n\tName :"<<name;
}
};
void main()
{
std s1,s2;
clrscr();
s1.read();
s1.print();
s2.read();
s2.print();
getch();
}
Run
#include<iostream.h>
#include<conio.h>
class sum
{
int i,j,k;
public:
void read();
int add();
};
void sum::read()
{
cout<<"\n\tEnter Two Number :"<<endl;
cin>>i>>j;
}
int sum::add()
{
k=i+j;
return(k);
}
void main()
{
sum s2;
clrscr();
s2.read();
cout<<"\n\tSum is :"<<s2.add();
getch();
}
Run
#include<iostream.h>
#include<conio.h>
#include<iomanip.h>
class sum
{
int i,j,k,tot;
public:
void read();
void write();
};
void sum::read()
{
cout<<"\n\tEnter Three Marks :"<<endl;
cin>>i>>j>>k;
}
void sum::write()
{
tot=i+j+k;
cout<<setw(4)<<i<<setw(4)<<j<<setw(4)<<k<<setw(5)<<tot<<endl;
}
void main()
{
sum s[3]; int i;
clrscr();
for(i=0;i<3;i++)
{
s[i].read();
}
for(i=0;i<3;i++)
{
s[i].write();
} Run
getch();
}
Static Variable
#include<iostream.h>
#include<conio.h>
class item
{
static int c;
public:
void get()
{
c++;
}
void put()
{
cout<<"\n\t"<<c;
}
};
int item::c; //initialized to zero
void main()
{
item A,B,C;
clrscr();
A.get();
A.put();
B.get();
B.put();
C.get();
C.put();
getch();
}
Run
Object As Arguments
class rect
{
private:
int l;
public:
void setdata(int a)
{
l=a;
}
void length(rect r1,rect r2)
{
l=r1.l+r2.l;
}
void showdata()
{
cout<<" Length :"<<l<<endl;
}
};
void main()
{
rect r1,r2,r3;
clrscr();
r1.setdata(5);
r1.showdata();
r2.setdata(6);
r2.showdata();
r3.length(r1,r2);
r3.showdata();
getch();
}
Run
Constructor and Destructor
As general rule, an object's constructor is called when the
Run
#include<iostream.h>
#include<conio.h>
class tollbooth
{
private:
unsigned int no_cars;
double money;
public:
tollbooth()
{
no_cars=0;
money=0;
}
void payingcar()
{
no_cars++;
money+=.5;
}
void nopaycar()
{
no_cars++;
}
void display()
{
cout<<"Number of cars passed by : "<<no_cars;
cout<<endl<<"Amount collected : Rs."<<money;
}
};
void main()
{
tollbooth t1;
char key;
clrscr();
do
{
key=getche();
if(key=='p')
t1.payingcar();
if(key=='n')
t1.nopaycar();
}while(key!=27);
t1.display();
getch();
} Run
Constructor Overloading
#include<iostream.h>
#include<conio.h>
class sum
{
int i,j,k;
public:
sum()
{
i=10; j=20;
}
sum(int x)
{
i=10; j=x;
}
sum(int a,int b)
{
i=a; j=b;
}
void print()
{
k=i+j;
cout<<"\n\tSum is :"<<k;
}
};
void main()
{
sum s1;
sum s2(9);
sum s3(5,8);
clrscr();
s1.print();
s2.print();
s3.print();
getch(); Run
}
Destructor
#include<iostream.h>
#include<conio.h>
class sum
{
int i,j,k;
public:
sum()
{
i=90;
j=23;
}
sum(sum &s1)
{
i=s1.i;
j=s1.j;
}
~sum()
{
cout<<"\n\tDeleted";
}
void write()
{
k=i+j;
cout<<"\n\tSum is :"<<k;
}
};
void main()
{
sum s;
sum s2(s);
clrscr();
s.write();
s2.write(); Run
getch();
}
Friend Functions
It is possible to grant nonmember function access to the
private members of class by using friend .A friend function
has access to all private and protected members of the
class for which it is friend .
Run
Friend Classes
It is possible for one class to be friend of another class. When
this is the case, the friend class and all of its member
Late Binding
#include<iostream.h>
#include<conio.h>
class rect
{
private:
int l,b;
public:
void set_data(int,int);
void show_data();
};
void rect::set_data(int l,int b)
{
this->l=l;
this->b=b;
}
void rect::show_data()
{
cout<<"\n\tLength :"<<this->l;
cout<<"\tBreadth :"<<this->b<<endl;
}
void main()
{
rect r;
clrscr();
r.set_data(12,254);
r.show_data();
getch();
} Run
Inheritance
1.Single Inheritance
2.Multi Level Inheritance
3.Hierarchy Inheritance
4.Multiple Inheritance
5.Hybrid Inheritance
#include<iostream.h>
#include<conio.h>
class sum
{
int i,j,k;
public:
void read()
{
cout<<"\n\tEnter Two Number :"<<endl;
cin>>i>>j;
}
void write()
{
k=i+j;
cout<<"\n\tSum is :"<<k;
}
};
class sub:public sum
{
int i,j,k;
public:
void read1()
{
cout<<"\n\tEnter Two Number :"<<endl;
cin>>i>>j;
}
void write1()
{
k=i-j;
cout<<"\n\tSub is :"<<k;
}
};
void main()
{
sub s2;
clrscr();
s2.read();
s2.write();
s2.read1();
s2.write1();
getch();
}
Run
#include<iostream.h>
#include<conio.h>
class sum
{
int i,j,k;
public:
void read()
{
cout<<"\n\tEnter Two Number :"<<endl;
cin>>i>>j;
}
void write()
{
k=i+j;
cout<<"\n\tSum is :"<<k;
}
};
class sub:public sum
{
int i,j,k;
public:
void read1()
{
cout<<"\n\tEnter Two Number :"<<endl;
cin>>i>>j;
}
void write1()
{
k=i-j;
cout<<"\n\tSub is :"<<k;
}
};
class mul:public sub
{
int i,j,k;
public:
void read2()
{
cout<<"\n\tEnter Two Number :"<<endl;
cin>>i>>j;
}
void write2()
{
k=i*j;
cout<<"\n\tMul is :"<<k;
}
};
void main()
{
mul s2;
clrscr();
s2.read();
s2.write();
s2.read1();
s2.write1();
s2.read2();
s2.write2();
getch();
}
Run
#include<iostream.h>
#include<conio.h>
class sum
{
int i,j,k;
public:
void read()
{
cout<<"\n\tEnter Two Number :"<<endl;
cin>>i>>j;
}
void write()
{
k=i+j;
cout<<"\n\tSum is :"<<k;
}
};
class sub:public sum
{
int i,j,k;
public:
void read1()
{
cout<<"\n\tEnter Two Number :"<<endl;
cin>>i>>j;
}
void write1()
{
k=i-j;
cout<<"\n\tSub is :"<<k;
}
};
class mul:public sum
{
int i,j,k;
public:
void read2()
{
cout<<"\n\tEnter Two Number :"<<endl;
cin>>i>>j;
}
void write2()
{
k=i*j;
cout<<"\n\tMul is :"<<k;
}
};
void main()
{
sub s1;
clrscr();
s1.read();
s1.write();
s1.read1();
s1.write1();
mul s2;
s2.read();
s2.write();
s2.read2();
s2.write2();
getch();
} Run
#include<iostream.h>
#include<conio.h>
class sum
{
int i,j,k;
public:
void read()
{
cout<<"\n\tEnter Two Number :"<<endl;
cin>>i>>j;
}
void write()
{
k=i+j;
cout<<"\n\tSum is :"<<k;
}
};
class sub
{
int i,j,k;
public:
void read1()
{
cout<<"\n\tEnter Two Number :"<<endl;
cin>>i>>j;
}
void write1()
{
k=i-j;
cout<<"\n\tSub is :"<<k;
}
};
class mul:public sum,public sub
{
int i,j,k;
public:
void read2()
{
cout<<"\n\tEnter Two Number :"<<endl;
cin>>i>>j;
}
void write2()
{
k=i*j;
cout<<"\n\tMul is :"<<k;
}
};
void main()
{
mul s2;
clrscr();
s2.read();
s2.write();
s2.read1();
s2.write1();
s2.read2();
s2.write2();
getch();
}
Run
Hybrid Inheritance or Virtual Base Class
#include<iostream.h>
#include<conio.h>
class baseA
{
public:
int varA;
};
class baseB: virtual public baseA
{
public:
int varB;
};
class baseC: virtual public baseA
{
public:
int varC;
};
class deriD:public baseB,public baseC
{
public:
int varD;
};
void main()
{
deriD dobj;
clrscr();
dobj.varA=10;
cout<<"\n\t"<<dobj.varA;
getch();
}
Run
Virtual Function
Example
Run
Polymorphism
1.Polymorphism means one name having multiple forms.
2.It allows us to have more than one function with the
same name in a program.
3.It also allows overloading of operators, so that an
operation can exhibit different behaviors in different
instances.
Example:
Draw ()
Run
Operator Overloading
Run
#include<iostream.h>
#include<conio.h>
class rectangle
{
private:
int length,breadth;
public:
rectangle(int,int);
~rectangle()
{
cout<<"Delete";
}
void operator++();
void operator++(int); // + operator overloading
void show_sides();
};
rectangle::rectangle(int a,int b)
{
length=a;
breadth=b;
}
void rectangle::operator++()
{
cout<<"prefix increment";
length++;
breadth++;
}
void rectangle::operator++(int)
{
cout<<"postfix increment";
length++;
breadth++;
}
void rectangle::show_sides()
{
cout<<"length :"<<length<<"breadth :"<<breadth<<endl;
}
void main()
{
clrscr();
rectangle r1(10,20);
r1.show_sides();
r1++;
r1.show_sides();
++r1;
r1.show_sides();
getch();
}
Run
#include<iostream.h>
#include<string.h>
#include<conio.h>
class string
{
private:
char str[30];
public:
string()
{
strcpy(str,""); // null value assignment
}
void operator=(char *cptr)
{
strcpy(str,cptr);
}
string operator+(string t1)
{
string t2;
strcpy(t2.str,str);
strcat(t2.str,t1.str);
return t2;
}
void show_string(char *obj)
{
cout<<obj<<str<<endl;
}
};
void main()
{
clrscr();
string s1,s2,s3;
s1=" Sachin";
s2=" Tendulkar";
s3= s1+s2;
s1.show_string(" string 1");
s2.show_string(" string 2");
s3.show_string(" string 3");
getch();
}
Run
Files
Obj.close();
in >>item >>cost;
cout <<item <<" "<<cost <<"\n";
in >>item >>cost;
cout <<item <<" "<<cost <<"\n";
in.close();
getch();
return 0;
}
Run
fstream Functions
feof()
get()
put()
getline()
read()
write()
peek()
flush()
flush()
char fname[50];
char str;
infile.open(fname);
if(infile.fail())
{
cout<<"File does not exist ";
getch();
exit(1);
}
while(!infile.eof())
{
infile.get(str);
cout<<str;
}
infile.close();
getch();
}
Run
#include<iostream.h>
#include<fstream.h>
#include<conio.h>
void main()
{
fstream file;
ifstream f("cpp45.cpp");
char bu[80];
int l=1;
clrscr();
while(f)
{
f.getline(bu,80);
cout<<"line : "<<l++<<"\t"<<bu<<"\n";
}
f.close();
getch(); Run
}
#include<iostream.h>
#include<fstream.h>
#include<stdlib.h>
#include<conio.h>
void main()
{
clrscr();
ofstream outfile;
ifstream infile;
char source[50],target[10];
char ch;
clrscr();
int no=10;
display(no);
data<int,float> n ;
n.store(4,5.5) ;
n.disp();
data<float,int> f ;
f.store (3.5,4) ;
f.disp() ;
getch() ;
}
Run
#include<iostream.h>
#include<conio.h>
template<class R>
class test
{
R data;
public:
void getdata();
void putdata();
};
template<class R>
void test<R>::getdata()
{
cout<<"\nEnter the data :";
cin>>data;
}
template<class R>
void test<R>::putdata()
{
cout<<"\nData is :"<<data<<endl;
}
void main()
{
test<int>t1;
test<double>t2;
test<char[]>t3;
clrscr();
t1.getdata();
t1.putdata();
t2.getdata();
t2.putdata();
t3.getdata();
t3.putdata();
getch();
}
Run
Linked List using C++
#include<iostream.h>
#include<conio.h>
#include<process.h>
#include<string.h>
class student
{
private:
char name[25];
public:
student(){}
student(char str[])
{
strcpy(name,str);
}
void getdata()
{
cout<<"Enter the name of the student";
cin>>name;
}
void putdata()
{
cout<<"Name of the student : "<<name<<endl;
}
};
class project
{
private:
char title[50];
public:
project(){}
project(char str[])
{
strcpy(title,str);
}
void getdata()
{
cout<<"Enter the project title";
cin>>title;
}
void putdata()
{
cout<<"Title of the project : "<<title<<endl;
}
};
class node : public student, public project
{
public:
node *next;
node()
{
next = NULL;
}
node(char name[],char title[]) : student(name), project(title)
{
next = NULL;
}
void getdata()
{
student::getdata();
project::getdata();
}
void putdata()
{
student::putdata();
project::putdata();
cout<<endl;
}
};
class list
{
node *start,*ptr;
public:
list()
{
start = NULL;
}
void add()
{
node *fresh;
fresh = new node();
fresh->getdata();
fresh->next = NULL;
if(start == NULL)
start = fresh;
else
{
for(ptr=start;ptr->next!=NULL;ptr=ptr->next);
ptr->next=fresh;
}
}
void display()
{
for(ptr=start;ptr!=NULL;ptr=ptr->next)
ptr->putdata();
}
};
void main()
{
list l1;
char choice;
clrscr();
while(1)
{
cout<<"1. Add details"<<endl;
cout<<"2. Display"<<endl;
cout<<"3. Exit"<<endl;
cout<<"Enter a choice";
cin>>choice;
switch(choice)
{
case '1' : l1.add();
break;
case '2' : clrscr();
l1.display();
break;
case '3' : exit(1);
}
}
}
Run
# include <iostream.h>
# include <conio.h>
class data
{
private :
int num ;
public :
data(int n=0)
{
num=n ;
}
void store(int n)
{
num=n ;
}
int get()
{
return num ;
}
void show()
{
cout << num << "->" ;
}
};
class node : public data
{
public :
node *next ;
node()
{
store(0) ;
next=NULL ;
}
};
class list
{
public :
node *start, *ptr ;
list()
{
start = NULL ;
ptr = new node() ;
}
void add(int no)
{
node *fresh ;
fresh = new node() ;
fresh->store (no) ;
if (start==NULL)
start = fresh ;
else
{
for (ptr=start ; ptr->next!=NULL ; ptr=ptr->next) ;
ptr->next=fresh ;
}
}
void insert(int no,int pos)
{
int i;
node *fresh,*old;
for(i=0,ptr=start;i<pos-2;ptr=ptr->next,i++);
old=ptr->next;
fresh=new node();
fresh->store(no);
ptr->next=fresh;
fresh->next=old;
}
void del(int no)
{
node *tmp;
ptr=start;
while(ptr->next->get()!=no)
ptr=ptr->next;
tmp=ptr->next->next;
delete ptr->next;
ptr->next=tmp;
}
void display()
{
for (ptr=start ; ptr!=NULL ; ptr=ptr->next)
ptr->show() ;
}
};
void main()
{
clrscr() ;
list obj1 ;
int num,pos;
char choice;
do
{
cout<<"Enter a choice"<<endl;
cout<<"1. Add"<<endl;
cout<<"2. Insert"<<endl;
cout<<"3. Delete"<<endl;
cout<<"4. Display"<<endl;
cin>>choice;
switch (choice)
{
case '1' : cout<<"Enter the number to add";
cin>>num;
obj1.add(num);
break;
case '2' : cout<<"Enter the number to insert";
cin>>num;
cout<<"Enter the position";
cin>>pos;
obj1.insert(num,pos);
break;
case '3' : cout<<"Enter the number to delete";
cin>>num;
obj1.del(num);
break;
case '4' : obj1.display();
break;
default : cout<<"Wrong entry";
}
cout<<"Do you want to continue (Y/N)";
cin>>choice; Run
}while(choice=='y'||choice=='Y');
}