Anda di halaman 1dari 119

d a t

a p r o

Computer specialization

Page No: 1

C++

1,0
Assem
Machine
Language
Assem
Assembly
language
Proced
Procedure oriented
Object oriented
The above picture shows the development of the computer software.
Earliest computers were programmed in binary.
Mechanical switches were used to load the program.
o Ex: machine language.
Next assembly language was introduced, Mnemonic codes were
used to interact with the computer.
In 60s and 70s structured programming (POP) was introduced.
Functions, procedures and sub-routines were introduced to
solve the problems easily.
Complications in POP given birth OOP.
Procedure oriented programming:
Cobol, c, Fotran, Foxpro are commonly known as POP.
Primary focus on functions and procedures.
While developing a procedure very little attention is given to
data i.e data is given a second class status.
Whole importance is on doing things.
In multi function program many important data items are places
as global, so that they can be accessed by all the functions
and procedures.
Data moves openly around the system from one function to
another.
Global X=20

F1

F2

F3

Many procedures access the same data so that the way data is
stored becomes critical

Developed by: Atish Jain


Intelligents are not born, they are made

d a t
Page No: 2

a p r o

Computer specialization

Object oriented programming(OOP):

The fundamental Idea behind OOP is to combine both data and


functions that operate on the data as a single unit.
A,B
F1()
F2()

DATA

Functions operating
On that data

OOP treats data as a critical element in the program


development and doesnt allow it to move freely around the
system.
In OOP the main concentration is on data items rather than
procedures.
Functions that operate on the data of an object are tied
together in the data structure.
Data is hidden and cannot accessed by external functions.

What is CPP:
C++ is an object oriented programming language. It was developed by
Bjarne Stroustrupe at AT&T bell laboratories, in Murray hill, new
jersey, U.S.A in 1980s.
Initially it was named C with classes. Later in 1983 the
name was changed to C++.
The idea of CPP comes from the Cs increment operator ++.
So it is known as incremented version of C.
C++ is a super set of C. all syntaxs of c can be applied
to C++ also. There fore every valid C program is a c++ program too.

The other languages which support OOP are:


1. Small talk
2. Object pascal
3. Java
4. charm++ etc...
The 3 most important that facilities that c++ adds to C are:
1. Classes.
2. Function overloading.
3. Operator overloading.
These features enable us to create abstract data types, inherit
properties from existing data types and support polymorphism. Thus
making C++ a truly object oriented programming language.

Developed by: Atish Jain


Intelligents are not born, they are made

d a t
Page No: 3

a p r o

Computer specialization

Characteristics of Object oriented programming language:


Object:
Objects are basic run time entities in a object oriented
programming system. In a structured programming a problem is solved
by approached by dividing it into functions. But in OOP the problem
is divided into objects. Thinking in terms of objects rather than
functions make the designing of a program easier. Objects contains
data and instructions to manipulate that data. An object takes up
some space in the main memory. They should match real world objects
such as banks, emp details.
Class:
A class is a user defined data type that is used to define an
object. An object is a variable of class type.
Data encapsulation:
The wrapping of data and functions into a single unit is known as
data encapsulation.
Data abstraction:
It means the way data is represented in the main memory and things
in terms what operations can be performed on the data. Un wanted
data is hidden from the user.
Polymorphism:
It is derived from a Greek word poly means many and morphs means
forms, the ability to take more than one meaning.
Inheritance:
This is a process in which objects of one class acquires the
properties of another class.
Structure of C++ program:
C++ is also a collection of functions. With the special main() it
may contain.
Include files
Class declaration
Member function definitions
Main function program
In C++ the main function is also accepts arguments and return a
value the operating system. If it is not returning a value then
should be written as void main().

Developed by: Atish Jain


Intelligents are not born, they are made

d a t

a p r o

Computer specialization

Page No: 4

Tokens:
The smallest individual items in program are known as tokens. C++
has the following tokens.
Keywords
Identifiers
Variables
Constants
Strings
Operators
Keywords:
Keywords also known as reserved words whose meaning is predefined
to the compiler. There are 48 keywords in C++. 32 of C and 16 New
of C++.
Identifiers:
Identifiers refer to the names of variables, functions, arrays,
classes etc.
Rules for declaring identifiers:
a) Only alphabets, digits, and underscore are permitted.
b) The identifier name should start with an alphabet.
c) Upper case and lower case letters are distinct
d) A declared keyword cannot be used as a identifier name.
Variable:
It is the name of the memory location where constants are stored.
Value of a variable changes during the execution of the program.
Ex: X=20

Variable name
Constant:
The value of a constant doesnt change during the program
execution.
Ex: X=20

Constant value
Datatype:
It specifies what type of data that a variable will hold.

Developed by: Atish Jain


Intelligents are not born, they are made

d a t

a p r o

Computer specialization

Page No: 5

C++ program features:


1. It is a collection of functions.
2. Every program should have one main().
3. Statements are terminated by semicolon.
4. C++ is a free form language.
Comments:
C++ introduces new comment symbol ( // ).
// double slash
It is used for single line comment.
Ex:// This is my first
// C++ program
Multiple comments are given by a /**/
/* This is
My first
C++ program */

Classification of data types


C++ Data types

User defined

Structures
Unions
Classes
Enumerations

Predefined

Integral
type

Derived

Floating
type

Arrays
Functions
Pointers
Reference

Void
float
int

double

char

Developed by: Atish Jain


Intelligents are not born, they are made

d a t

a p r o

Computer specialization

Page No: 6

The modifiers signed, unsigned, short and long are applied to get
additional datatypes.
DATATYPE
SIZE
RANGE
Char
1
-128 to +127
Unsigned char
1
0 to 255
Signed char
1
-128 to +127
Int
2
-32768 to +32767
Short int
2
-32768 to +32767
Signed int
2
-32768 to +32767
Signed short int
2
-32768 to +32767
Unsigned int
2
0 to 65535
Unsigned short int
2
0 to 65535
Long int
4
-2147483648 to
+2147483647
Float
4
3.4e-38 to 3.4e+37
Double
8
1.7e-308 to 1.7e+307
Long double
10
3.4e-4932 to 1.1e+4932
iostream.h file:# include <iostream.h>
# include :- preprocessor directive, which adds the contents of
iostream.h file to the program file.
Basic input/output statements:
1. cout: (console output)
This statement is used to display a message or value of a
variable on the console(Monitor).
Syntax:
Cout<<Message<< <variable>;
<<- insertion operator or put to operator
Ex:
int a=10;
cout<< As value is :<<a;
2. cin: (console input)
This statement is used to accept a value into a
Variable.
Syntax:
cin>> <variable>
>> - Extraction operator or get from operator
Ex:
int a;
cin>>a;

Developed by: Atish Jain


Intelligents are not born, they are made

d a t

a p r o

Computer specialization

Page No: 7

void:
To specify return type of a function with it is not returning
any value.
To indicate an empty argument list to a function.
Ex:
void Function_name(void)
Operators in C++:
C++ has a rich set of operators. All c operators are valid in C++.
We have seen two operators insertion (<<) and extraction (>>). The
other operators are :
1.
2.
3.
4.
5.
6.
7.
8.

:: - scope resolution operator


:: * - pointer to member declarator
->* or .* - pointer to member operator
NEW memory allocation operator
DELETE memory release operator
Endl (or) \n line feed operator
SETW field width operator
\t for tab

// 1.Sample program
// Program name: hello.cpp
# include <iostream.h>
# include <conio.h>
void main()
{
clrscr();
cout<<"Hello";
getch();
}
Editor commands:
ALT+f3
F6
F5
F2
F9
CTRL+F9-

To
To
To
To
To
To

close the window


switch between the windows
zoom the windowr
save
compile
execute

Developed by: Atish Jain


Intelligents are not born, they are made

d a t
Page No: 8

a p r o

Computer specialization

// Program to add two no's

# include <iostream.h>
# include <conio.h>
void main()
{
int a,b,c;
a=b=c=0;
clrscr();
cout<<"Enter a no:";
cin>>a;
cout<<"Enter another no:";
cin>>b;
c=a+b;
cout<<"The result is:"<<c;
getch();
}
Flexible declaration of variables:
In c language all the variables must be declared before the first
executable statement, but c++ allows us to declare a variable at
run time.
/* Program to print Amount for
the inputed Rate and Quantity */

# include <iostream.h>
# include <conio.h>
void main()
{
clrscr();
float rate;
cout<<"Enter rate:";
cin>>rate;
int qty;
cout<<"Enter quantity:";
cin>>qty;
float amt=rate*qty;
cout.precision(2);
cout<<"Amount is:"<<amt;
getch();
}

Developed by: Atish Jain


Intelligents are not born, they are made

d a t
Page No: 9

a p r o

Computer specialization

Reference variables:
A reference variable is an alias (in c typedef)(alternate name) for
a existing variable.
Syntax:
<Datatype> & <reference variable name>=variable;
// Program name: d:\atish\cpp\refe.cpp
# include <iostream.h>
# include <conio.h>
void main()
{
clrscr();
int a=100;
int &b=a;
cout <<"A value is:"<<a<<endl;
b=b+100;
cout<<"A value is:"<<a;
getch();
}
Constant qualifier:
The keyword CONST if present before the Datatype of a variable,
it specifies that the value of the variable will not change through
out the program.
Syntax:<const Datatype> <variable name>= <value>
// Program to find the area of a circle
// Program name:d:\atish\cpp\const_ac.cpp
# include <iostream.h>
# include <conio.h>
void main()
{
clrscr();
float r,a;
const float p=3.14;
cout<<"Enter radius:";
cin>>r;
a=p*r*r;
cout<<"Area is:"<<a;
getch();
}

Developed by: Atish Jain


Intelligents are not born, they are made

d a t
Page No: 10

a p r o

Computer specialization

// Program to split the decimal no


// Program no:d:\atish\cpp\no.cpp
# include <iostream.h>
# include <conio.h>
void main()
{
float no;
clrscr();
cout<<"Enter a decimal no:";
cin>>no;
int n1=int(no);
float n2=no-n1;
cout<<n1<<endl;
cout<<n2;
getch();
}
// Program to display hours and minutes from the total input
minutes

Scope resolution operator:


C++ supports a mechanism to access a global variable from a
function in which a local variable is defined with the same name as
global variable.
It is achieved using the scope resolution operator ( :: ).
Syntax::: <variable name>
// Program d:\atish\cpp\sro.cpp
# include <iostream.h>
# include <conio.h>
int a=10;
void main()
{
int a=20;
clrscr();
cout<<"Local A is:"<<a<<endl;
cout<<"Global A is:"<<::a;
getch();
}

Developed by: Atish Jain


Intelligents are not born, they are made

d a t

a p r o

Computer specialization

Page No: 11

Control structures:
Some it is necessary to perform repeated actions or skip some
statements, for these actions certain statements are available.
These statements alters the flow of execution of the programs.
Control structures are of two types:
A) Decision making statements
a. Simple if
b. If with else statement
c. Multiple if
d. Nested if
e. Switch case
B) Looping constructs
a. While loop
b. Do..while loop
c. For loop
Relational operators or comparison operators:
< - greater than
< - less than
>= - greater than equal to
<= - less than equal to
== - equal to
!= - not equal to
Logical operators:
And - &&
Or - ||
Not - !
* These are used to combine the conditions
Syntax for decision making statements:
1. Simple if
if <condition>
{
stmt1;
stmt2;
}

Developed by: Atish Jain


Intelligents are not born, they are made

d a t
Page No: 12

a p r o

Computer specialization

2. if with else
if <condition>
{
stmt1;
stmt2;
}
else
{
stmt3;
stmt4;
}
3.Multiple if
if <condition>
{
stmt1;
stmt2;
}
else if<condition>
{
stmt3;
stmt4;
}
else
{
stmt5;
stmt6;
}
4. Nested if
if <condition>
if <condition>
{
stmt1;
stmt2;
}
else
{
stmt3;
stmt4;
}
else
{
stmt5;
stmt6;

Developed by: Atish Jain


Intelligents are not born, they are made

d a t
Page No: 13

a p r o

Computer specialization

}
Switch case:
Switch case is the replacement for multiple ifs
Syntax:switch ( expr )
//expr only characters or integer for comparing
{
case <expr>: stmt1; break;
case <expr>: stmt2; break;
----------------default : stmt;
}
Type casting:
It means changing the Datatype of a variable at run time.
Ex:int a=100,b=365,c=0;
c=a*b; // Gives wrong output
c=a*(long)b; // C type CPP
c=a*long(b); // C++ type
//program for typecasting
# include <iostream.h>
# include <conio.h>
void main()
{
float no;
clrscr();
no=(float)5/2;
cout<<"no is "<<no;
getch();
}
/*no=5.0/2.0*/
//program for typecasting
# include <iostream.h>
# include <conio.h>
void main()
{
float no;
clrscr();
no=5.0/2.0;
//dont assign direct initialization

Developed by: Atish Jain


Intelligents are not born, they are made

d a t

a p r o

Computer specialization

Page No: 14
cout<<"no is "<<no;
getch();
}

Syntax for Looping constructs:


1. while loop:

while <condition>
{
stmt1;
stmt2;
}
loop is pretested
Control enters into the body of the loop after ckecking the
condition.

2. do..while
do
{
stmt1;
stmt2;
}while<condition>;

loop is post tested


Control enters into the body of the loop with out checking the
condition the condition.
Body of the loop will be executed at least for one though the
condition is not satisfied.

3. for loop
for (expr1;expr2;expr3)
{
stmt1;
stmt2;
}

For loop is mainly used when the number of repetitions are


known in advance
Expr1- initialization
Expr2- condition
Expr3- incrementation/decrementation

Developed by: Atish Jain


Intelligents are not born, they are made

d a t
Page No: 15

a p r o

Computer specialization

Functions:
A number of statements grouped into a single unit is referred to as
a function. Functions are mainly used for modular programming.
A function or a sub program is written to avoid writing
instructions each time for repeated tasks. The instructions are
written only once and can be called any number of times.
There are two types of functions:
Library functions:
These are coming along with the compiler.
Ex:- getch(), gets(), etc
User defined functions:
These are defined by the user to perform specific tasks. Every
program should have one main() and N number of user defined
functions.
A function may or may not accept arguments and may or may not
return values. A function can return one and only one value.
// Adding of two no's using functions
// Program name: fun_add2.cpp
# include <iostream.h>
# include <conio.h>
void main()
{
int a,b,c;
int add(int,int); // Function declaration
clrscr();
cout<<"Enter a no:";
cin>>a;
cout<<"Enter another no:";
cin>>b;
c=add(a,b); // Function invocation(or)function calling
cout<<"The result is:"<<c;
getch();
}
int add(int x,int y)
{
int z;
z=x+y;
return(z);
}

// Function definition(or)function body

Developed by: Atish Jain


Intelligents are not born, they are made

d a t

a p r o

Computer specialization

Page No: 16

Explanation:
There are 3 steps in functions.
Function declaration:
The declaration describes function name, no. of arguments, type of
argument and a return value. This feature is also called function
prototype.
Syntax:< return type >

function name (arg list);

ex:int add(int,int);

return
type

fun.. name

data type of
the arguments

Function invocation:
It means calling the function. The arguments passed at function
invocation are known as actual arguments.
Syntax:<variable name> = function name( arg1,arg2,. . . );
ex:c=add(a,b);
Actual arguments
The returning value of add() is assigned to variable C.

Function definition:
It means defining the user defined function.
Syntax:< return type > functions name(arg1,arg2,. . .)
{
----------}
Ex:int add(int x,int y)
{
int z;
Formal arguments
z=x+y;
return(z);
}

Developed by: Atish Jain


Intelligents are not born, they are made

d a t
Page No: 17

a p r o

Computer specialization

copy of the variables a,b is taken in x and y


z is the local variable used with in the function.
The returning value is returned with return statement

When a function is called the flow of execution of main program is


halted and the control passes to the function along with the values
of actual arguments. The actual arguments are copied to formal
arguments, statements with in the function (UDF) are executed and
the return statement takes back the control to the main function
along with a value (if any).
main()
{
..
..
f1();
.
}

f1()
{..

Actual arguments:
The arguments that are passed from the calling function to call()
are called actual arguments. The actual arguments can be constants.
Ex:c=add(a,b);
c=add(10,20);
Formal arguments:
The arguments that are received in the function definition are
known as formal arguments.
In the above example x and y are formal arguments.
Note:The data type, order of appearance and the no of actual arguments
must be same as those of formal arguments
Functions are called in two ways:
Call by value
Call by reference
Call by value:
Call by value means calling the function by passing the value to
it.
// Program implement call by value
// Program name: cal_by_v.cpp
# include <iostream.h>
# include <conio.h>
void main()
{

Developed by: Atish Jain


Intelligents are not born, they are made

d a t
Page No: 18

a p r o

Computer specialization

void swap(int , int );


int a=10,b=20;
clrscr();
cout<<"The values are:"<<a<<" "<<b;
swap(a,b);
cout<<"\nSwapped values are:"<<a<<" "<<b;
getch();
}
void swap(int x,int y)
{
int t;
t=x;
x=y;
y=t;
return;
}
Call by reference:
Call by reference using reference operator.
// Program for call by reference using reference operator
// Program name: swap_ref.cpp
# include <iostream.h>
# include <conio.h>
void main()
{
int a=10,b=20;
void swap(int&,int&);
clrscr();
cout<<"Values before swap()"<<endl;
cout<<"A="<<a<<endl;
cout<<"B="<<b;
swap(a,b);
cout<<endl<<"Values after swap()"<<endl;
cout<<"A="<<a<<endl;
cout<<"B="<<b;
getch();
}
void swap(int &x,int &y)
{
int t=x;
x=y;
y=t;
return;

Developed by: Atish Jain


Intelligents are not born, they are made

d a t
Page No: 19

a p r o

Computer specialization

/*call by reference*/
#include<iostream.h>
#include<conio.h>
void swap(int *a,int *b)
{
int t;
t=*a;
*a=*b;
*b=t;
}
void main()
{
clrscr();
int a=10,b=20;
cout<<"before: "<<a<<" "<<b<<endl;
swap(&a,&b);
cout<<"after : "<<a<<" "<<b<<endl;
getch();
}
// Biggest of 10 nos using operator
//Program name: d:\atish\cpp\big10_re.cpp
# include <iostream.h>
# include <conio.h>
void main()
{
int no,b=0;
void big(int,int&);
clrscr();
for(int i=0;i<5;i++)
{
cout<<"Enter a no:";
cin>>no;
big(no,b);
}
cout<<"Biggest no is:"<<b;
getch();
}
void big(int no,int &b)
{

Developed by: Atish Jain


Intelligents are not born, they are made

d a t

a p r o

Computer specialization

Page No: 20
if (no>b)
b=no;
}

Categories of functions:
A function may or may not accept arguments and may or may not
return values. Depending upon this functions exists four types.
1. Accepting arguments and returning a value
Ex:# include <iostream.h>
# include <conio.h>
void main()
{
int a=10,b=20;
int add(int,int);
clrscr();
int c;
c=add(a,b);
cout<<The result is:<<c;
getch();
}
int add(int x,int y)
{
return(x+y);
}
2. Accepting arguments and not returning a value
Ex:# include <iostream.h>
# include <conio.h>
void main()
{
int a=10,b=20;
void add(int,int);
clrscr();
add(a,b);
getch();
}
void add(int x,int y)
{
int z;

Developed by: Atish Jain


Intelligents are not born, they are made

d a t

a p r o

Computer specialization

Page No: 21

z=x+y;
cout<<The result is:<<z;
}

3. Not accepting arguments and returning a value


Ex:# include <iostream.h>
# include <conio.h>
void main()
{
int c;
int add(void);
clrscr();
c=add();
cout<<add of 2 numbers<<c;
getch();
}
int add()
{
int a=10,b=20,c;
c=a+b;
return(c);
}

4. Neither accepting nor returning a value


Ex:# include <iostream.h>
# include <conio.h>
void main()
{
void add(void);
clrscr();
add();
getch();
}
void add(void)
{
int a=10,b=20,c;
c=a+b;
cout<<The result is:<<c;
}

Developed by: Atish Jain


Intelligents are not born, they are made

d a t

a p r o

Computer specialization

Page No: 22

Return by reference:
A function can also return a reference.
// Return by reference
//Program name: d:\atish\cpp\big2_ref.cpp
# include <iostream.h>
# include <conio.h>
void main()
{
int a,b;
int & max(int &,int &);
clrscr();
cout<<"Enter a no:";
cin>>a;
cout<<"Enter a no:";
cin>>b;
cout<<"Biggest no is:"<<max(a,b);
getch();
}
int & max(int &x,int&y)
{
if (x>y)
return(x);
else
return(y);
}
Inline functions:
An inline function is a function that is expanded in line when it
is invoked. i.e. The compiler replaces the function call when the
corresponding function code (definition).
Syntax:
inline
{

<function name> (arg1,agr2,)


---------------------

}
When a normal function is called the flow of execution of main
program is halted and the control passes to the function along with
the actual parameters. After the completion of the function control

Developed by: Atish Jain


Intelligents are not born, they are made

d a t
Page No: 23

a p r o

Computer specialization

returns back to the main program along with a value (if any). This
process takes some time.
An inline function is same as a normal function in all the ways,
but the keyword inline is kept before the function name.
The keyword inline sends a request to the compiler but not a
command. The compiler may ignore the request if the function is too
large.

Note: These are special type of functions which are stored along
main function. So program can execute statement of these functions
alone main function. We can call inline function many times without
jumping and control statements.
Rules:
1. It must have very less no of statements
2. It does not contain any loops
3. We can not declare large objects or variables
4. Inline functions must be declared in globel section.
5. For functions returning a value if a return statement exists.
Some
1.
2.
3.

situations where inline functions may not work.


If the function contains static variables.
If the Inline functions are recursive.
For functions returning values If a loop, switch or goto
exists.

Inline functions are best reserved for small and frequently used
functions. They are declared at global level.
//program to add 2 float numbers
#include<iostream.h>
#include<conio.h>
inline float sum(float a,float b)
{
return a+b;
}
void main()
{
float s=0;
s=sum(4.6f,9.2f);
cout<<s;
getch();
}
// Inline function
// Program name: inline.cpp
# include <iostream.h>
# include <conio.h>

Developed by: Atish Jain


Intelligents are not born, they are made

d a t
Page No: 24

a p r o

Computer specialization

inline calc(int x,int y)


{
return(x*y);
}
void main()
{
int r,q;
clrscr();
cout<<"Enter rate:";
cin>>r;
cout<<"Enter quantity:";
cin>>q;
cout<<"Amount is:"<<calc(r,q);
getch();
}
//program for amstrong number(1,153,371,407.)
153=1*1*1+5*5*5+3*3*3=153
#include<iostream.h>
#include<conio.h>
inline int cube(int n)
{
return n*n*n;
}
void main()
{
int n,s=0;
clrscr();
cout<<"enter a number";
cin>>n;
for(int t=n;t>0;t/=10)//t=t/10 ;
s=s+cube(t%10);
if(s==n)
{
cout<<"amstrong number";
}
else
{
cout<<"not a amstrong number";
}
getch();
}
/*max value find by using inline function*/

Developed by: Atish Jain


Intelligents are not born, they are made

d a t

a p r o

Computer specialization

Page No: 25

#include <iostream.h>
#include<conio.h>
inline int Max(int x, int y)
{
return (x > y)? x : y;
}
void main( )
{
clrscr();
cout << "Max (20,10): " << Max(20,10) << endl;
cout << "Max (0,200): " << Max(0,200) << endl;
cout << "Max (100,1010): " << Max(100,1010) << endl;
getch();
}
Write a program to print area of a circle using inline function.
Default arguments in functions:
In C when a function is defined to receive two arguments, then we
have to pass two arguments whenever we call the function. But C++
allows us to call a function without specifying all its arguments.
1. The function assigns a default value to the parameter which
does not have a matching argument in the function call.
2. Default values are specified when the function is declared.
3. Default values are specified in the same way as variables are
defined and initialized.
Ex:Float inrest(int,int,float=1.20);
(a)
(b)

amt=intrest(100,1);
amt=intrest(100,1,2);

In (a) one argument is missing so the function uses default


value, therefore r=1.20
In (b) no argument is missing therefore r=2

Note: Default values are added from right to left. We can not
provide a default value to a particular argument in the middle of
the list.
//sum of numbers by using default arguments
#include<iostream.h>

Developed by: Atish Jain


Intelligents are not born, they are made

d a t
Page No: 26

a p r o

Computer specialization

#include<conio.h>
int sum(int a,int b,int c=0,int d=0)
{
return(a+b+c+d);
}
void main()
{
clrscr();
cout<<sum(2,5)<<endl;
cout<<sum(10,5,6)<<endl;
cout<<sum(1,2,3,4)<<endl;
getch();
}
//program for draws a box with the coordinates
#include<iostream.h>
#include<conio.h>
void box(int l=10,int t=10,int r=50,int b=50)
{
cout<<"draws a box with the
coordinates:"<<l<<','<<t<<','<<'\t'<<r<<'\t'<<b<<endl;
}
void main()
{
clrscr();
box();
box(2,1);
box(1,2,3);
box(1,2,3,4);
getch();
}
// Program name: d:\atish\cpp\defa3.cpp
# include <iostream.h>
# include <conio.h>
float intrest(int a=1000,int b=2,float c=1.20)
{
Return (a*b*c/100);
}
void main()
{
clrscr();
cout<<"Ramesh:"<<intrest(100,2)<<endl;

Developed by: Atish Jain


Intelligents are not born, they are made

d a t
Page No: 27

a p r o

Computer specialization

cout<<"Hari:"<<intrest(100,2,1)<<endl;
cout<<"Sunil:"<<intrest(200)<<endl;
cout<<"Kavitha:"<<intrest();
getch();
}
float intrest(int p,int n,float r)
{
return(p*n*r/100);
}
// Program to print lines
// Program name: d:\atish\cpp\defa_arg.cpp
# include <iostream.h>
# include <conio.h>
void main()
{
void print(char='*' ,int=50);
clrscr();
print();
// with out any argument
print('#');
print('!',10);
print('a',60);
print(2);
getch();
}
void print(char ch,int i)
{
for(;i>=1;i--)
cout<<ch;
cout<<endl;
}
Function overloading:
It means using the same function name to create functions that
accepts different number of arguments, different types arguments
and performing different tasks.
This is also known as function polymorphism in oop.
Note: by same function name,with same operation by passing
different arguments to that operations is called function
overloading.

//sum of numbers by using function overloading

Developed by: Atish Jain


Intelligents are not born, they are made

d a t
Page No: 28

a p r o

Computer specialization

#include<iostream.h>
#include<conio.h>
int sum(int a,int b)
{
return a+b;
}
int sum(int a,int b,int c)
{
return a+b+c;
}
float sum(int a,float b)
{
return a+b;
}
float sum(float a,float b)
{
return a+b;
}
float sum(float a,int b)
{
return a+b;
}
void main()
{
clrscr();
cout<<sum(1,2)<<endl;
cout<<sum(1,2,3)<<endl;
cout<<sum(1,2,3.6f)<<endl;
cout<<sum(2.3f,1.2f)<<endl;
cout<<sum(9.6f,3)<<endl;
getch();
}
// Function overloading
// Program name: d:\atish\cpp\fo_area.cpp
#include<iostream.h>
#include<conio.h>
class area
{
float a;
public:
void calc()
{
a=0;
cout<<"shape unknown"<<endl;

Developed by: Atish Jain


Intelligents are not born, they are made

d a t
Page No: 29

a p r o

Computer specialization

cout<<"area:"<<a<<endl;
}
void calc(int p)
{
a=p*p;
cout<<"shape is square"<<endl;
cout<<"area:"<<a<<endl;
}
void calc(int p,int q)
{
a=p*q;
cout<<"shape is rectangle"<<endl;
cout<<"area:"<<a<<endl;
}
void calc(float r)
{
a=3.14*r*r;
cout<<"shape is circle"<<endl;
cout<<"area:"<<a<<endl;
}
};
void main()
{
clrscr();
area x;
x.calc();
x.calc(10,20);
x.calc(25);
x.calc(9.6f);
/*float must be declared like this other wise memory allocated for
double datatype by default.*/
getch();
}

//program for area of shapes by using method overloading


# include <iostream.h>
# include <conio.h>
float area(int);
// function declarations
int area(int,int);
float area(float);
void main()
{
float s=4.5;
clrscr();
cout<<"Area of rectangle:"<<area(3,4)<<endl;
cout<<"Area of circle:"<<area(5)<<endl;

Developed by: Atish Jain


Intelligents are not born, they are made

d a t

a p r o

Computer specialization

Page No: 30

cout<<"Area of square:"<<area(s);
getch();
}
float area(int r)
{
return(3.14*r*r);
}
int area(int l,int b)
{
return(l*b);
}
float area(float s)
{
return(s*s);
}
// Function overloading
//Program name: d:\atish\cpp\fun_over.cpp
# include <iostream.h>
# include <conio.h>
int add(int,int);
int add(int,int,int);
float add(float,float);
void main()
{
clrscr();
cout<<"Result is:"<<add(5,6)<<endl;
cout<<"Result is:"<<add(10,25,10)<<endl;
cout<<"Result is:"<<add((float)12.5,(float)12.5);
getch();
}
int add(int x,int y)
{
return(x+y);
}
int add(int x,int y,int z)
{
return(x+y+z);
}
float add(float x,float y)

Developed by: Atish Jain


Intelligents are not born, they are made

d a t

a p r o

Computer specialization

Page No: 31
{
return(x+y);
}
Classes and objects:

A structure in C is a collection of similar or dissimilar data


types. In oop functions are included with in the structures. The
functions defined with in a structure will have special
relationship with the structure elements present within the
structure. Placing of data and functions (that work upon the data)
together into a single entity is the central idea in OOP.
Format:
class <class name>
{
private: datamembers;
member functions;
public:

datamembers;
member functions;

};

Class declaration is similar to structure declaration. The


body of a class is enclosed within a code block and terminated
by semicolon;
Variables inside the class are called as data members.
Functions declared inside the class are called as member
functions or methods.
The data members and member functions are usually declared
under two sections namely Private and public.
Private and public are known as access specifiers.
The access specifiers are followed by a colon(:).
The members that have been declared as private can be accessed
only by the member functions of the same class.
Data hiding(private area) is the key feature in OOP
Private data members cant be accessed from out side of the
class.
The keyword private in class declaration is optional because
the members of the class are private by default and public in
structures.
If both labels are missing then all the members are private
and that class is completely hidden form the out side world.

No Entry to private
area for out side
members.

Developed by: Atish Jain


Intelligents are not born, they are made

d a t

a p r o

Computer specialization

Page No: 32

DATA
FUNCTIONS
Entry to public area
for all out side
members

DATA
FUNCTIONS

Only the member functions (public area) can have access to the
private data members and private functions. The data members
are usually declared as private and the member functions are
at public section.

A class declaration has two parts


1. Class definition
2. Class function definition
ex:class emp
{
private:
int empno;
char name[20];
public :
void getdata();
void dispdata();
};
Creating objects:
Once a class has been declared we can create variables of that
type by using the class name.
In cpp class variables are known as objects. The declaration of
object is similar to that of a variable fo any basic type.
int a,b;
Emp e1,e2;
In the above declaration a&b are ordinary variables of integer
type and e1 and e2 are objects of type emp.
Accessing class members:
The private data of a class can be accessed only trough the
member functions of the same class.
If a variable is declared at public section it can be accessed
directly by the objects.
Ex:-

Developed by: Atish Jain


Intelligents are not born, they are made

d a t

a p r o

Computer specialization

Page No: 33
class test
{
int a,b;

// private by default

public:
int x;
};
void main()
{
test t;
t.a=10;
t.x=20;
}
Defining member functions:
Member functions can be defined in two places
1. Inside the class
2. Out side the class
1. Inside the class:
When a member function is defined with in a class it is
treated as inline function. There fore all the restrictions
and limitations that apply to an inline function are also
applicable here.
Normally small functions are defined inside the class.
// Program to demonstrate classes and objects
// Program name :d:\atish\cpp\classes
# include <iostream.h>
# include <conio.h>
class item
{
private:
int qty;
float rate,amt;
public:
void setdata(int x,float y)
{
qty=x;
rate=y;
}
void calcdata()
{

Developed by: Atish Jain


Intelligents are not born, they are made

d a t
Page No: 34

a p r o

Computer specialization

amt=rate*qty;
}
void dispdata()
{
cout<<"Amount to be paid:"<<amt<<endl<<endl;
}
void getdata()
{
cout<<"Enter quantity:";
cin>>qty;
cout<<"Enter rate:";
cin>>rate;
}
}; // end of class
void main()
{
item i1,i2,i3;
clrscr();
i1.setdata(5,2.55);
i1.calcdata();
i1.dispdata();
i2.getdata();
i2.calcdata();
i2.dispdata();
getch();
}
// Program to calculate area and perimeter of three
rectanlges
// Program name : d:\atish\cpp\classes\rectangl.cpp
# include <iostream.h>
# include <conio.h>
class rectangle
{
int len,br;
// private data members
public :
void getdata()
{
cout<<endl<<"Enter length:";
cin>>len;
cout<<"Enter breadth:";
cin>>br;
}
void setdata(int l,int b)

Developed by: Atish Jain


Intelligents are not born, they are made

d a t

a p r o

Computer specialization

Page No: 35
{

len=l;
br=b;
}
void dispdata()
{
cout<<endl<<"Length:"<<len;
cout<<endl<<"Beadth:"<<br<<endl;
}
void area_peri()
{
int a,p;
a=len*br;
p=2*(len+br);
cout<<"Area :"<<a<<endl;
cout<<"Perimeter:"<<p<<endl;
}
};
void main()
{
rectangle r1,r2,r3; //Defines three objects of class
rectangle
clrscr();
r1.setdata(10,20);
r1.dispdata();
r1.area_peri();
r2.setdata(5,8);
r2.dispdata();
r2.area_peri();
r3.getdata();
r3.dispdata();
r3.area_peri();
getch();
}
Note:
The functions setdata(), getdata(), dispdata() and
area_peri() behaves like inline functions because they are
defined with in the class.

Out side the class definition:

Developed by: Atish Jain


Intelligents are not born, they are made

d a t

a p r o

Computer specialization

Page No: 36

Member functions that are declared inside the class inside


the class can be defined out side the class definition.
Format:<return type> <class name> :: function_name()
{
------------}
The sro(::) tells the complier that the function
function_name belongs to the class class_name.
When a function is defined out side the class then it is an
ordinary function. The functions defined out side the class
can be made inline by using the keyword inline
// Program to calculate total and average for inputed three
subjects.
// Program name : d:\atish\cpp\classes\totavg.cpp
# include <iostream.h>
# include <conio.h>
class std
{
private:
int m,p,c;
float t,a;
public :
void getdata();
void tot_avg();
void display();
};
void std :: getdata()
{
cout<<endl<<endl<<"Enter maths marks:";
cin>>m;
cout<<"Enter physics marks:";
cin>>p;
cout<<"Enter chemistry marks:";
cin>>c;
}
void std :: tot_avg()
{
t=m+p+c;
a=t/3;

Developed by: Atish Jain


Intelligents are not born, they are made

d a t

a p r o

Computer specialization

Page No: 37
}

void std :: display()


{
cout<<"Total is:"<<t<<endl;
cout<<"Average is:"<<a;
}
void main()
{
std s1,s2;
clrscr();
s1.getdata();
s1.tot_avg();
s1.display();
s2.getdata();
s2.tot_avg();
s2.display();
getch();
}
Nesting of member functions:
We have seen that member functions are called by using objects of
that class using dot (.) operator.
A member function can be called by using its name inside another
member function of the same class. This is known as nesting of
member functions.
// nesting of member functions.
// Program name: d:\atish\cpp\classes\big2.cpp
# include <iostream.h>
# include <conio.h>
class test
{
private:
int a,b;
public :
void accept();
int big();
void display();
};
void test :: accept()
{
cout<<"Enter two no's:";
cin>>a>>b;

Developed by: Atish Jain


Intelligents are not born, they are made

d a t
Page No: 38

a p r o

Computer specialization

}
inline int test :: big()
{
if (a>b)
return(a);
else
return(b);
}
void test :: display()
{
cout<<"Biggest no is:"<<big();
}
void main()
{
test x;
clrscr();
x.accept();
x.display();
getch();
}
Programs:
1. write a program to check whether the
odd
2. Write a program to check whether the
or not
3. Write a program to check whether the
ve or neutral
4. Biggest of 3 nos
5. Check whether the character is vowel
6. Find out no of words in string
7. Convert lower case to upper case and
8. Convert the string to proper case.
9. Write a program to check whether the
not.
10.Write a program to check whether the
palindrome or not.

given no is even or
given no is prime
given no is + ve or

or consonant
vice versa
no is Armstrong or
string is

Private member functions:


A private member function can only be called by using another
function i.e its members of its class. Even an object cannot
invoke a private function using dot operator.

Developed by: Atish Jain


Intelligents are not born, they are made

d a t
Page No: 39

a p r o

Computer specialization

// Program name: d:\atish\cpp\classes\prifun.cpp


# include <iostream.h>
# include <conio.h>
class test
{
private:
int a;
void read();
public :
void store()
{
read();
}
void display()
{
cout<<"A="<<a;
}
};
void test :: read()
{
a=10;
}
void main()
{
test x;
clrscr();
x.store();
x.display();
getch();
}
Arrays with in a class:
Arrays can also be used as a member variable with In a class.
// Program name: d:\atish\cpp\classes\arr_c.cpp
# include <iostream.h>
# include <conio.h>
class sample
{
private:
int arr[10];
public:
void store();
void disp();
};
void sample :: store()

Developed by: Atish Jain


Intelligents are not born, they are made

d a t

a p r o

Computer specialization

Page No: 40
{

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


{
cout<<"Enter a no:";
cin>>arr[i];
}
}
void sample :: disp()
{
for (int i=0;i<10;i++)
cout<<"The element is:"<<arr[i]<<endl;
}
void main()
{
sample x;
clrscr();
x.store();
x.disp();
getch();
}

write a program to fill the array with even numbers


Write a program to search for a number in the array of 10
elements.
Write a program to sort the array elements.

Array of objects:
# include <iostream.h>
# include <conio.h>
class emp
{
private:
int empno;
char name[20];
int sal;
public :
void store();
void display();
};
void emp :: store()
{
cout<<"Enter empno:";
cin>>empno;

Developed by: Atish Jain


Intelligents are not born, they are made

d a t

a p r o

Computer specialization

Page No: 41

cout<<"Enter name:";
cin>>name;
cout<<"Enter salary:";
cin>>sal;
}
void emp :: display()
{
cout<<endl<<"Empno:"<<empno;
cout<<endl<<"Name :"<<name;
cout<<endl<<"Salaty:"<<sal;
}
void main()
{
emp e[5];
int i;
clrscr();
for(i=0;i<5;i++)
e[i].store();
for(i=0;i<5;i++)
e[i].display();
getch();
}
Write a program to accept and display details of 10 items
Item code
Description
Rate
Quantity
Amount
Passing objects as arguments to functions:
class test
{
int a;
public:
void setdata(int x)
a
{
30
a=x;
}
void dispdata()
{
cout<<endl<<"The value is :"<<a;
}

z.sum(x,y)

x.a
10

y.a
20

Developed by: Atish Jain


Intelligents are not born, they are made

d a t
Page No: 42

a p r o

Computer specialization

void sum(test,test);

//function declaration

};
void test :: sum(test p,test q)
{
a=p.a+q.a;
}
void main()
{
test x,y,z;
clrscr();
x.setdata(15);
y.setdata(20);
z.sum(x,y);
x.dispdata();
y.dispdata();
z.dispdata();
getch();
}
Program to work with functions which return objects
# include <iostream.h>
# include <conio.h>
class test
{
int no;
public:
void setdata(int x)
{
no=x;
}
void dispdata()
{
cout<<endl<<"The value is :"<<no;
}
test sum(test);

//declaration

};
test test :: sum(test y)
{
test t;
t.no=y.no+no;

Developed by: Atish Jain


Intelligents are not born, they are made

d a t
Page No: 43

a p r o

Computer specialization

return(t);
}
void main()
{
test x,y,z;
clrscr();
x.setdata(15);
y.setdata(20);
z=x.sum(y);
x.dispdata();
y.dispdata();
z.dispdata();
getch();
}
Data members:
A data member of a class can be qualified as static. Static data
member of useful when all the objects of the class shares a common
item of information.
Note:
We use thses variables to store common values of all objects a
single location these are special varibales which are store
separitly from all class objects
Use as
1. Common (common value storage)
2. Count (no of values counting)
class

No
Name
course name

No
Name
course name

No
Name
course name

No
Name
course name
MCA

/*without static variable values*/


#include<iostream.h>
#include<conio.h>
class student
{
int no;
public:
student()
{

Developed by: Atish Jain


Intelligents are not born, they are made

d a t

a p r o

Computer specialization

Page No: 44

no=0;
no++;
}
void getdata()
{
cout<<"a value "<<no<<endl
}
};
void main()
{
student s;
clrscr();
s.getdata();
student t;
t.getdata();
student r;
r.getdata();

getch();
}
Output:
A value:1
A value:1
A value:1
/*simple count program in cpp by using static varibales*/
#include<iostream.h>
#include<conio.h>
class student
{
static int no;
public:
student()
{
no++;
}
void getdata()
{
cout<<"a value "<<no<<endl
}
};
int student::no=0;
void main()
{

Developed by: Atish Jain


Intelligents are not born, they are made

d a t

a p r o

Computer specialization

Page No: 45
student s;
clrscr();
s.getdata();
student t;
t.getdata();
student r;
r.getdata();
getch();
}
Output:
A value:1
A value:2
A value:3

/*small difference in above program object creation*/


#include<iostream.h>
#include<conio.h>
class student
{
static int no;
public:
student()
{
no++;
}
void getdata()
{
cout<<"a value "<<no<<endl
}
};
int student::no=0;
void main()
{
student s,t,r;
clrscr();
s.getdata();
t.getdata();
r.getdata();

getch();
}
Output:

Developed by: Atish Jain


Intelligents are not born, they are made

d a t

a p r o

Computer specialization

Page No: 46
a value:3
a value:3
a value:3

//program for static varibales


#include<iostream.h>
#include<conio.h>
class student
{
int rno;
char name[30];
static char sname[30];
static int count;
public:
student()
{
count++;
}
void getstu()
{
cout<<"enter rno name sname";
cin>>rno>>name>>sname;
}
void showstu()
{
cout<<rno<<"\t"<<name<<"\t"<<sname<<endl;
cout<<"count is "<<count<<endl;
}
};
char student::sname[30]="";
int student::count=0;
void main()
{
student s1;
clrscr();
s1.getstu();
s1.showstu();
student s2;
s2.getstu();
s2.showstu();
s1.showstu();
getch();
}
Characteristics:

Developed by: Atish Jain


Intelligents are not born, they are made

d a t

Computer specialization

Page No: 47

a p r o

It is initialized to zero when first object of its class is


created.
Only one copy of that member is created of the entire class
It is visible with in the class but its life time is entire
program.
Static data members must be defined outside the class as
Ex:<Return type> <class name> :: <static variable>
# include <iostream.h>
# include <conio.h>
class test
{
private:
static int count;
int a;
public:
void store(int x)
{
a=x;
count++;
}
void display()
{
cout<<"Count is:"<<count<<endl;
}
};
int test :: count;

// defining the static data member

void main()
{
test p,q,r;
clrscr();
p.store(10);
q.store(20);
r.store(30);
p.display();
q.display();
r.display();
getch();
}
Program to find sum of 10 inputed array elements.
Note: it is essential to start constructors because the sum
variable must be initialized to 0.

Developed by: Atish Jain


Intelligents are not born, they are made

d a t
Page No: 48

a p r o

Computer specialization

Constructors:
CPP provides a special member function called constructor
which enables an object to initialize itself when it is
created. This is known as automatic initialization of objects.
It is special because its name is the same as the class name.
the constructor is invoked whenever an object of its
associated class is created. It is called constructor because
it constructs the values of data members of the class. There
are three types of constructors.
Default constructor:
A constructor which does not accept any parameters.
Parameterized constructor:
A constructor that accepts arguments is called parameterized
constructor.
Copy constructor:
A copy constructor takes a reference to an object of the same
class as itself as an argument.
Characteristics of constructors:
A constructor should be declared in the public section
They are invoked automatically when the objects are created
They do not have return type, not even void and therefore they
can not return values.
/*simple constractor declare in class*/
#include<iostream.h>
#include<conio.h>
class hello
{
public:
hello()
{
cout<<"hello";
}
};
void main()
{
clrscr();
hello t;
getch();
}

Developed by: Atish Jain


Intelligents are not born, they are made

d a t

a p r o

Computer specialization

Page No: 49

// Program demonstrate DFAULT CONSTRUCTOR


// Program name: d:\atish\cpp\classes\constru.cpp
# include <iostream.h>
# include <conio.h>
class sample
{
int m,n;
public:
sample(); // Constructor declaration
void display()
{
cout<<"Value of M and N:"<<m<<endl;
cout<<"Value of M and N:"<<n;
}
};
sample :: sample()
{
m=n=0;
}
void main()
{
sample x;
clrscr();
x.display();
getch();
}

Parameterized constructor:
// parameterized constructors
// Program name: d:\atish\cpp\classes\paracon.cpp
# include <iostream.h>
# include <conio.h>
class sample
{
int m,n;
public :
sample(int x,int y);
void display()
{
cout<<"Value of M:"<<m<<endl;
cout<<"Value of N:"<<n<<endl<<endl;
}

Developed by: Atish Jain


Intelligents are not born, they are made

d a t
Page No: 50

a p r o

Computer specialization

};
sample :: sample (int x,int y)
{
m=x;
n=y;
}
void main()
{
clrscr();
sample x(100,200); // constructor called implicitly
sample y=sample(5,10); // constructor called explictly
cout<<"Object 1:\n";
x.display();
cout<<"Object 2:\n";
y.display();
getch();
}
Copy constructor:
// Copy constructor
// Program name: d:\atish\cpp\classes\copycon.cpp
# include <iostream.h>
# include <conio.h>
class sample
{
int m,n;
public :
sample(int x,int y);
void display()
{
cout<<"Value of M:"<<m<<endl;
cout<<"Value of N:"<<n<<endl<<endl;
}
};
sample :: sample (int x,int y)
{
m=x;
n=y;
}
void main()
{
clrscr();
sample x(100,200); // constructor called implicitly
sample y(x); // or sample y=x
cout<<"Object 1:\n";

Developed by: Atish Jain


Intelligents are not born, they are made

d a t
Page No: 51

a p r o

Computer specialization

x.display();
cout<<"Object 2:\n";
y.display();
getch();
}
/*combination of constractor types*/
#include<iostream.h>
#include<conio.h>
class shape
{
int l,w;
public:
shape()
//defaulconstractor
{
l=w=0;
}
shape(int p)
{
l=w=p;
//paramerarisedd constractor
}
shape(int p,int q)
{
l=p;
w=q;
}
shape(shape &s)
//copy constractor
{
l=s.l;
w=s.w;
}
void area()
{
cout<<"area : "<<l<<"*"<<w<<"="<<l*w<<endl;
}
};
void main()
{
shape x,y(10),z(10,50);
shape m(y);
clrscr();
x.area();
y.area();
z.area();
m.area();
getch();

Developed by: Atish Jain


Intelligents are not born, they are made

d a t
Page No: 52

a p r o

Computer specialization

Program to print sum of inputed 10 nos


To print Fibonacci series till 100
To print factorial of input no
Sum and average of even nos and odd nos from the input N
nos

Header file creation:


/*simple program*/
#include<iostream.h>
class test
{
public:
void fun()
{
Cout<<hello * am in fun();
}
}
/*supporting program*/
#include<conio.h>
#includetest.cpp
void main()
{
clrscr();
test t;
t.fun();
getch();
}

Destructor:
Destructor is used to destroy the objects that haven been created
by constructor. It is also a member function whose name is same as
the class name but is preceded by tilde (~).
Format:~ <Destructor name>
{
---}
A destructor never takes any arguments nor it returns any value. It
is automatically invoked by the compiler when the control comes out
from the program ( block or function).

Developed by: Atish Jain


Intelligents are not born, they are made

d a t
Page No: 53

a p r o

Computer specialization

It is a special method of class which will run automatically during


object delation at end of program we place ~(tiled) symbol before
class name to create destructor.
// program name: destroy.cpp
# include <iostream.h>
# include <conio.h>
class sample
{
int i;
public :
sample()
{
i=0;
cout<<"Inside the constructor"<<endl;
cout<<"Value of I is:"<<i;
}
~sample()
{
cout<<"\nInside the destructor"<<endl;
}
};
void main()
{
clrscr();
sample x;
x.disp();
getch();
}
/*values calling after destractor calling time*/
#include<iostream.h>
#include<conio.h>
class number
{
int a,b;
public:
number()
{
cout<<"enter 2 numbers";
cin>>a>>b;
}
~number()
{
cout<<a<<" "<<b;
}

Developed by: Atish Jain


Intelligents are not born, they are made

d a t
Page No: 54

a p r o

Computer specialization

};
void main()
{
clrscr();
number p,q,r;
cout<<"end of program"<<endl;
getch();
}
Friend functions:
The private data members of a class are accessible only by the
member functions of that class.
From the above point it is clear that non-member functions(
functions outside the class) have no access to private data
members. Cpp allows an outside function to access private data
members if it is declared as friend to that class. A function is
declared as friend by using the keyword Friend.
Syntax:class sample
{
private:
----public:
friend void test();
};
A friend function is not a member function to any class but is
allowed to access the private data members.
Characteristics of friend functions:

The keyword friend is used to declare a friend function.


An outside function is made friendly by declaring that
function friend to that class.
A friend function is not an member function though it is
declared in that class.
Usually friend functions accepts objects as arguments.
It is invoked like a normal function with out the help of any
object
It can not be accessed by an object
Friend of one class can be friend of another class or all the
classes in one program, such a friend is known as GLOBAL
FRIEND.
//Friends are non-members hence do not get this pointer.
Friend can be declared anywhere (in public, protected or
private section) in the class.

Developed by: Atish Jain


Intelligents are not born, they are made

d a t

a p r o

Computer specialization

Page No: 55

It is a special function which will run by using members of more


than one class.it is not a member of any class but it can access
private and public members of both classes.

// Accessing private data members by friend function.


// Program name: d:\atish\cpp\classes\friend1.cpp
# include <iostream.h>
# include <conio.h>
class test
{
private:
int a;
public :
void store()
{
cout<<"Enter a no:";
cin>>a;
}
friend void disp(test x)
{
cout<<"The value is:"<<x.a;
}
};
void main()
{
test s;
clrscr();
s.store();
disp(s);
getch();
}
// Friend function to calculate mean
// Program name : d:\atish\cpp\classes\frined2.cpp
# include <iostream.h>
# include <conio.h>
class test
{
private:

Developed by: Atish Jain


Intelligents are not born, they are made

d a t

a p r o

Computer specialization

Page No: 56
float a,b;
public :

void store()
{
cout<<"Enter a no:";
cin>>a;
cout<<"Enter a no:";
cin>>b;
}
friend float mean(test x);
};
float mean(test s)
{
return( (s.a+s.b)/2.0);
}
void main()
{
test s;
clrscr();
s.store();
cout<<"Mean value is:"<<mean(s);
getch();
}
Note: The keyword friend is not used In function definition.
// A function is friend to two classes
// Program name: d:\atish\cpp\classes\friend3.cpp
# include <iostream.h>
# include <conio.h>
class TWO; // forward declaration
class ONE
{
int x;
public:
void setvalue(int i)
{
x=i;
}
friend void max(ONE,TWO);
};
class TWO
{

// friend function declaration

Developed by: Atish Jain


Intelligents are not born, they are made

d a t
Page No: 57

a p r o

Computer specialization

int y;
public:
void setvalue(int i)
{
y=i;
}
friend void max(ONE,TWO);
};
void max(ONE o,TWO t) // definition of friend function
{
if (o.x==t.y)
cout<<"Both Objects are equal";
else
if (o.x>t.y)
cout<<"Maximum is:"<<o.x;
else
cout<<"Maximum is:"<<t.y;
}
void main()
{
clrscr();
ONE o; // o is object of class ONE
TWO t; // t is object of class TWO
int n1,n2;
cout<<"Enter two values:";
cin>>n1>>n2;
o.setvalue(n1);
t.setvalue(n2);
max(o,t); // calling friend function
getch();
}
//Calculating income tax for hero and heroine
// Program name: d:\atish\cpp\classes\hero_tax.cpp
# include <iostream.h>
# include <conio.h>
class heroine; // Forward declaration
class hero
{
private:
float income;
public:
hero()
// default constructor
{

Developed by: Atish Jain


Intelligents are not born, they are made

d a t
Page No: 58

a p r o

Computer specialization

income=600000;
}
friend void income_tax(hero a,heroine b);
};

// declaration

class heroine
{
private:
float income;
public:
heroine()
{
income=300000;
}
friend void income_tax(hero a,heroine b);
};

// declaration

void income_tax(hero a,heroine b)


{
float tax;
float income[]={a.income,b.income};
for (int i=0;i<2;i++)
{
if (income[i]<=100000)
tax=0;
else if (income[i]<=200000)
tax=income[i]*10/100;
else if (income[i]<=500000)
tax=income[i]*25/100;
else tax=income[i]*40/100;
cout<<"Income="<<income[i]<<"\t"<<"Tax="<<tax<<endl;
}
}
void main()
{
clrscr();
hero chiru;
heroine aishu;
income_tax(chiru,aishu);
getch();
}
/*friend function in private data*/
#include<iostream.h>

Developed by: Atish Jain


Intelligents are not born, they are made

d a t
Page No: 59

a p r o

Computer specialization

#include<conio.h>
class Box
{
private:
double wid;
friend void printWidth( Box b );
public:
void setWidth( double wid );
};
void Box::setWidth( double wid )
{
this->wid = wid;
}
void printWidth( Box b)
{
cout << "Width of box : " << b.wid <<endl;
}
void main( )
{
Box b;
clrscr();
b.setWidth(10.0);
printWidth( b );
getch();
}

/*FRIEND FUNCTION*/
#include<iostream.h>
#include<conio.h>
class marks;
class student
{
int rno;
char name[30];
float avg;
public:
void getval()
{
cout<<"enter rno, name";
cin>>rno>>name;
}
void showval()
{
cout<<"Rno:"<<rno<<"\nName:"<<name<<endl;

Developed by: Atish Jain


Intelligents are not born, they are made

d a t
Page No: 60

a p r o

Computer specialization

}
void friend result(student s,marks m);
};
class marks
{
int mt,p,c;
public:
void getmar()
{
cout<<"enter 3 values";
cin>>mt>>p>>c;
}
void showmar()
{
cout<<mt<<"\t"<<p<<"\t"<<c<<endl;
}
void friend result(student s,marks m)
};
void result(student s,marks m)
{
s.getval();
s.showval();
s.avg=(m.mt+m.p+m.c)/3;
if(s.avg<35)
cout<<"fail"<<endl;
else
cout<<"pass"<<endl;
m.showmar();
cout<<"avg: "<<s.avg<<endl;
};
void main()
{
student a;
marks b;
clrscr();
result(a,b);
getch();
}
Container ship:
When we declare object of a class inside another class then we can
call methods of inner class using objects of outer ans inner class
it is called container ship.
Syntax:
Class a
{

Developed by: Atish Jain


Intelligents are not born, they are made

d a t
Page No: 61

a p r o

Computer specialization

------}
Class b
{
----}
/*simple program for container ship just like enums*/
#include<iostream.h>
#include<conio.h>
class date
{
int dd,mm,yy;
public:
void getdata()
{
cin>>dd>>mm>>yy;
}
void show()
{
cout<<dd<<"/"<<mm<<"/"<<yy<<endl;
}
};
class emp
{
int eno;
char ename[10];
date dob,doj;
public:
void getemp()
{
cout<<"enter eno,ename: ";
cin>>eno>>ename;
cout<<"enter date of birth: ";
dob.getdata();
cout<<"enter date of join: ";
doj.getdata();
}
void show()
{
cout<<"eno:"<<eno<<endl;
cout<<"name"<<ename<<endl;
cout<<"dob:";
dob.show();
cout<<"\ndoj:";

Developed by: Atish Jain


Intelligents are not born, they are made

d a t

a p r o

Computer specialization

Page No: 62
doj.show();
}
};
void main()
{
emp e;
clrscr();
e.getemp();
e.show();
getch();
}

Inheritance:
The mechanism of deriving a new class from an old one is called
inheritance.

Re usability is another feature of OOP.


CPP classes can be reused in special ways.
Once a class has been written and tested, the data can be
activated by other programs. This is basically done by
creating new classes with reusing the properties of the
existing classes.
The old class is referred as the base class and the new class
is derived class.
A derived class inherits some or all of the data from the base
class.

Types of inheritance:
1. Single inheritance

3. Multilevel inheritance
A

Base class

Derived class

2. Multiple inheritance
A

4. Hierarchical inheritance
A

Developed by: Atish Jain


Intelligents are not born, they are made

d a t

a p r o

Computer specialization

Page No: 63

5. Hybrid inheritance(virtual inheritance)


C

Defining derived class:


A derived class is defined by specifying its relationship with the
base class in addition to its own details.
Format:
Private/public
class <class name> : <visibility specifier> <base class name>
{
--------}

The colon(:) indicates that the derived class name is derived


from the mentioned base class name.
The visibility mode is optional, if it is present it should be
private or public. Default is private.
When a base class is privately inherited by a derived class,
public members of the base class becomes private members of
the derived class and therefore the public members of the base
class can only be accessible by the member functions of the
derived class
Private

P
riva
te

Public

Private

Public

When the base class is publicly inherited then the public


members of the base class becomes public members of the
derived class and therefore they are accessible by the
objects.
Private

Public

P
ubli
c

Private

Public

Developed by: Atish Jain


Intelligents are not born, they are made

d a t

a p r o

Computer specialization

Page No: 64

Note:
In the above classes the private members of the base class are not
inherited. Therefore the private members of the base class will
never become members of the derived class.

1. Single inheritance:
A derived class with only one base class is called single
inheritance.
Main
sub
a

b
geta()
dispa()

P
riva
te

b
geta()
dispa()

c
getabc()
dispabc()

// Single inheritance
// Program name d:\atish\cpp\ih_singl.cpp
# include <iostream.h>
# include <conio.h>
class main
{ private:
int a;
public :
int b;
void geta()
{
cout<<"Enter value for a:";
cin>>a;
}
int dispa()
{ return(a);
}
};
class sub:private main
{
private:
int c;
public:
void getabc()
{

Developed by: Atish Jain


Intelligents are not born, they are made

d a t

a p r o

Computer specialization

Page No: 65

geta();
cout<<"Enter no's for b and c:";
cin>>b>>c;
}
void dispabc()
{
cout<<"A is:"<<dispa()<<endl;
cout<<"B is:"<<b<<endl;
cout<<"C is:"<<c<<endl;
}
};
void main()
{
clrscr();
sub x;
x.getabc();
x.dispabc();
getch();
}
Write a program to display student details.
Student
Rollno
Name
City

Marks
dos,win,cpp
total
average

Protected data members:


Private data members of the base class cannot be inherited,
therefore they are not available for the derived class directly.
CPP Provides the third visibility specifier called as protected
serves a limited purpose in inheritance.
The data members declared as protected are accessible by the member
functions with in its class and by any class derived from it.
class <class name>
{
Protected:
--------Public:
--------};

Developed by: Atish Jain


Intelligents are not born, they are made

d a t

a p r o

Computer specialization

Page No: 66

When a protected member is inherited in private mode, it becomes


private in derived class and therefore it is accessible by the
member functions of the derived class. It is not available for
further inheritance.
P
R
I
V
A
T
E

private
protected

public

private

protected
public

When a protected member is inherited in public mode, it becomes


protected in the derived class and therefore it is accessible by
the member functions of the derived class and it also ready for the
further inheritance.
private

P
U
B
L
I
C

protected

public

private

protected

public

Visibility of inherited members:


Derived class visibility

Base class visibility

Public derivation
Private
Not inherited
Protected
Protected
Public
Public
2. Multiple inheritance:

Private derivation
Not inherited
Private
Private

Protected derivation
Not inherited
Protected
Protected

A derived class with several base classes is called multiple


inheritance.
// Multiple inheritance
// program name d:\atish\cpp\classes\ih_mult1.cpp
# include <iostream.h>
# include <conio.h>
class main1
{

Developed by: Atish Jain


Intelligents are not born, they are made

d a t

a p r o

Computer specialization

Page No: 67
protected:
int x;
public:

void getx()
{
cout<<"Enter a no:";
cin>>x;
}
};
class main2
{
protected:
int y;
public:
void gety()
{
cout<<"Enter a no:";
cin>>y;
}
};
class sub: public main1,public main2
{
public:
void display()
{
cout<<"X is:"<<x<<endl;
cout<<"Y is:"<<y;
}
};
void main()
{
clrscr();
sub t;
t.getx();
t.gety();
t.display();
getch();
}
//Multiple inheritance:
# include <iostream.h>
# include <conio.h>
class student
{
protected:
int rollno;

Developed by: Atish Jain


Intelligents are not born, they are made

d a t
Page No: 68

a p r o

Computer specialization
char name[20];

public:
void getdata();
};
void student :: getdata()
{
cout<<"Enter rollno:";
cin>>rollno;
cout<<"Enter name:";
cin>>name;
}
class marks
{
protected:
int m,p,c;
public:
void getmarks()
{
cout<<"Enter marks for m,p,c:";
cin>>m>>p>>c;
}
};
class result : public student,public marks
{
private:
float tot,avg;
public:
void calc()
{
tot=m+p+c;
avg=tot/3;
}
void disp()
{
cout<<"Rollno:"<<rollno<<endl;
cout<<"Name:"<<name<<endl;
cout<<"Maths::"<<m<<endl;
cout<<"Physics:"<<p<<endl;
cout<<"Chemistry:"<<c<<endl;
cout<<"Total:"<<tot<<endl;
cout<<"Average:"<<avg;
}
};
void main()

Developed by: Atish Jain


Intelligents are not born, they are made

d a t

a p r o

Computer specialization

Page No: 69
{
clrscr();
result one;
one.getdata();
one.getmarks();
one.calc();
one.disp();
getch();
}

// multilevel inheritance
# include <iostream.h>
# include <conio.h>
# include <string.h>
class student
{
protected:
int rollno;
char name[20];
public:
void getstu(int r,char n[])
{
rollno=r;
strcpy(name,n);
}
void dispstu()
{
cout<<"Rollno :"<<rollno<<endl;
cout<<"Name :"<<name<<endl;
}
};
class marks : public student
{
protected :
int m,p,c;
public:
void getmarks()
{
cout<<"Enter marks for m,p,c:";
cin>>m>>p>>c;
}
void dispmarks()

Developed by: Atish Jain


Intelligents are not born, they are made

d a t

a p r o

Computer specialization

Page No: 70
{

cout<<"Maths:"<<m<<endl;
cout<<"Physics:"<<p<<endl;
cout<<"Chemistry:"<<c<<endl;
}
};

class result : public marks


{
private :
float tot,avg;
public:
void calc()
{
dispstu();
dispmarks();
tot=m+p+c;
avg=tot/3;
cout<<"total :"<<tot<<endl;
cout<<"Average:"<<avg;
}
};
void main()
{
clrscr();
result r;
r.getstu(101,"raj");
r.getmarks();
r.calc();
getch();
}

BANK
# include <iostream.h>
# include <conio.h>
class bank
{
protected:
int accno;
char name[20];

Accno
Name
bal

Getdet()
Dispdet()

DEPOSIT

WITHDRAWL

Accno, name, bal


Getdet(), dispdet()

Accno, name, bal


Getdet(), dispdet()

Amt, getdeposit()

Amt, by:
getwithdrawl
()
Developed
Atish Jain
Intelligents are not born, they are made

d a t

a p r o

Computer specialization

Page No: 71
int bal;
public:

void getdet()
{
cout<<"Enter account no:";
cin>>accno;
cout<<"Enter name:";
cin>>name;
cout<<"Enter balance:";
cin>>bal;
}
void dispdet()
{
cout<<"Account no:"<<accno<<endl;
cout<<"Name:"<<name<<endl;
cout<<"Balance:"<<bal<<endl<<endl;
}
};
class deposit :private bank
{
private:
int amt;
public:
void getdeposit()
{
getdet();
cout<<"Enter deposit amount:";
cin>>amt;
bal=bal+amt;
dispdet();
}
};
class withdrawl :private bank
{
private:
int amt;
public:
void getwithdrawl()
{
getdet();
cout<<"Enter withdrawl amount:";
cin>>amt;
bal=bal-amt;
dispdet();
}
};

Developed by: Atish Jain


Intelligents are not born, they are made

d a t

a p r o

Computer specialization

Page No: 72

void main()
{
clrscr();
deposit x;
withdrawl y;
x.getdeposit();
y.getwithdrawl();
getch();
}

Hybrid inheritance:
It is the combination of two or more inheritances.
Student

Marks

Sports

Result

Combination of Multiple and Multilevel inheritance.


// Hybrid inheritance
# include <iostream.h>
# include <conio.h>
class student
{
protected:
int rollno;
char name[20];
public:
void get()
{
cout<<"Enter Rollno:";
cin>>rollno;
cout<<"Enter name:";
cin>>name;
}

Developed by: Atish Jain


Intelligents are not born, they are made

d a t
Page No: 73

a p r o

Computer specialization

void disp()
{
cout<<endl;
cout<<"Rollno is:"<<rollno<<endl;
cout<<"Name is:"<<name<<endl;
}
};
class marks : public student
{
protected:
int m,p,c;
public:
void getmarks()
{
cout<<"Enter marks for Maths,Physics,and Chemistry:";
cin>>m>>p>>c;
}
void dispmarks()
{
cout<<"Maths:"<<m<<endl;
cout<<"Physics:"<<p<<endl;
cout<<"Chemistry:"<<c<<endl;
}
};
class sports
{
protected:
float score;
public:
void getscore()
{
cout<<"Enter the score for sports:";
cin>>score;
}
void dispscore()
{
cout<<"Score is:"<<score<<endl;
}
};
class result : public marks,public sports
{
float total;
public:
void display()
{
total=m+p+c+score;

Developed by: Atish Jain


Intelligents are not born, they are made

d a t

a p r o

Computer specialization

Page No: 74

cout<<"Total:"<<total;
}
};
void main()
{
result s1;
clrscr();
s1.get();
s1.getmarks();
s1.getscore();
s1.disp();
s1.dispmarks();
s1.dispscore();
s1.display();
getch();
}
/*ambiguity*/
In hybrid inheritance when we try to call methods of 1 st base
class using last child class object it gives an error it is called
ambiguity to solve this er must called those methods with
intermidate class name.
base

Base2

Base1

child

#include<iostream.h>
#include<conio.h>
class book
{
char bname[30];
float price;
public:
void getbook()
{
cout<<"enter book name and price";
cin>>bname;

Developed by: Atish Jain


Intelligents are not born, they are made

d a t
Page No: 75

a p r o

Computer specialization

cin>>price;
}
void showbook()
{
cout<<bname<<" "<<price<<"Rs"<<endl;
}
};
class author:public book
{
char aname[10];
int year;
public:
void getauth()
{
cout<<"enter author name and year";
cin>>aname>>year;
}
void showauth()
{
cout<<aname<<" wrote this in "<<year<<endl;
}
};
class publish:public book
{
char pname[10],address[30];
public:
void getpub()
{
cout<<"enter publisher name address";
cin>>pname>>address;
}
void showpub()
{
cout<<pname<<" published from "<<address<<endl;
}
};
class store:public author,public publish
{
char sname[30];
int n;
public:
void getst()
{
cout<<"enter store name and qty";
cin>>sname>>n;
}
void showst()

Developed by: Atish Jain


Intelligents are not born, they are made

d a t
Page No: 76

a p r o

Computer specialization

{
cout<<sname<<" contains "<<n<<" copies "<<endl;
}
};
void main()
{
clrscr();
store s;
s.author::getbook();
s.getauth();
s.getpub();
s.getst();
s.author::showbook();
s.showauth();
s.showpub();
s.showst();
getch();
}
Function overriding:
When both base class and child class have method with same name
child class object can access child class method only to use base
class method we give base class name to call base class method.
#include<iostream.h>
#include<conio.h>
class base
{
int a,b;
public:
void getval()
{
cout<<"enter 2 ints";
cin>>a>>b;
}
void calc()
{
cout<<"sum="<<a+b<<endl;
}
};
class child:public base
{
float c,d;
public:
void getdata()
{
cout<<"enter 2 floats";

Developed by: Atish Jain


Intelligents are not born, they are made

d a t
Page No: 77

a p r o

Computer specialization

cin>>c>>d;
}
void calc()
{
cout<<"mul="<<c*d<<endl;
}
};
void main()
{
clrscr();
child p;
p.getval();
p.getdata();
p.calc();
p.base::calc(); //for only super class not nessary for child class
getch();
}

Class pointer:
It is a pointer variable which can store address of object created
with same class we use operator to access class methods with
class pointer.
#include<iostream.h>
#include<conio.h>
class computer
{
char cname[30];
float price;
int qty;
public:3
void getcomp()
{
cout<<"enter computer name,price,qty";
cin>>cname>>price>>qty;
}
void showcomp()
{
cout<<cname<<"\t"<<price<<"\t"<<qty<<endl;
}
};
void main()
{
clrscr();
{
computer c,*p;

Developed by: Atish Jain


Intelligents are not born, they are made

d a t
Page No: 78

a p r o

Computer specialization

p=&c;
p->getcomp();
p->showcomp();
c.getcomp();
c.showcomp();
getch();
}
}

Function overriding with pointer:


In inheritance we can store address of base class and child class
pointer.when both classes have method with same name the base class
pointer can exiquit base class methods only.we cannot call child
class methods with base class pointer.

#include<iostream.h>
#include<conio.h>
class rest
{
int l,w;
public:
void calc()
{
cout<<"enter length, width";
cin>>l>>w;
cout<<"area"<<l*w<<endl;
}
};
class circle:public rest
{
float r;
public:
void calc()
{
cout<<"enter radious";
cin>>r;
cout<<"area:"<<3.14*r*r<<endl;
}
};
void main()
{
clrscr();
rest r,*p;
circle c,*q;

Developed by: Atish Jain


Intelligents are not born, they are made

d a t
Page No: 79

a p r o

Computer specialization

p=&r;
p->calc();
p=&c;
//base pointer stores child obj address
p->calc();
q=&c;
q->calc();
//q=&r;
//child pointer cannot store base obj address
getch();
}
Virtual function:
When both base class, child class have methods with same name the
base class pointer can called base class method only tp call child
class method we make base class method as virtual function with
virtual keybord it hipes base class method from child class object.
#include<iostream.h>
#include<conio.h>
class base
{
int a,b;
public:
void virtual calc()
{
cout<<"\n enter 2 numbers";
cin>>a>>b;
cout<<"\neven numbers.....";
for(int i=a;i<=b;i++)
if(i%2==0)
cout<<i<<"\t";
}
};
class child:public base
{
float c,d;
public:
void calc()
{
cout<<"enter 2 float values";
cin>>c>>d;
cout<<"product:"<<c*d<<endl;
}
};
void main()
{
clrscr();
child c;

Developed by: Atish Jain


Intelligents are not born, they are made

d a t
Page No: 80

a p r o

Computer specialization

base *p;
p=&c;
p->calc();
base b;
p=&b;
p->calc();
getch();
}
/*in class function getting virtual base products*/
#include<iostream.h>
#include<conio.h>
class abst
{
int a,b;
public:
void getval()
{
cout<<"enter 2 values";
cin>>a>>b;
}
void showval()
{
cout<<a<<"\t"<<b<<endl;
}
void virtual big(char ch)=0;//pure virtual function
};
class num:public abst
{
char c;
public:
void big(char ch)
{
c=ch;
if((c>='a')&&(c>='z'))
c=c-32;
cout<<c;
}
};
void main()
{
num n;
//abst x;
//cannot create
object for astract class
abst *p;
clrscr();

Developed by: Atish Jain


Intelligents are not born, they are made

d a t

a p r o

Computer specialization

Page No: 81
p=&n;
p->getval();
p->showval();
p->big('Y');
p->big('R');
getch();
}

Virtual base classes:

rno, name

STUDENT
rno, name

rno, name

MARKS

SPORTS
rno, name

rno, name

RESULT

The above inheritance is the combination of three inheritances ie.


Multilevel, multiple and hierarchical.
The duplication of inherited members due to this multiple path can
be avoided by making the common base class while declaring the base
classes.
Class student
{
-}
class marks : virtual public student
{
-}
class sports : public virtual student
{
-}
class result : public marks,public sports
{
/*only one copy of student will be inherited */
}

Developed by: Atish Jain


Intelligents are not born, they are made

d a t

a p r o

Computer specialization

Page No: 82
#include<iostream.h>
#include<conio.h>

class student
{
int rno;
public:
void getnumber()
{
cout<<"Enter Roll No:";
cin>>rno;
}
void putnumber()
{
cout<<"\n\n\tRoll No:"<<rno<<"\n";
}
};
class test:virtual public student
{
public:
int part1,part2;
void getmarks()
{
cout<<"Enter Marks\n";
cout<<"Part1:";
cin>>part1;
cout<<"Part2:";
cin>>part2;
}
void putmarks()
{
cout<<"\tMarks Obtained\n";
cout<<"\n\tPart1:"<<part1;
cout<<"\n\tPart2:"<<part2;
}
};
class sports:public virtual student
{
public:
int score;
void getscore()
{
cout<<"Enter Sports Score:";

Developed by: Atish Jain


Intelligents are not born, they are made

d a t

a p r o

Computer specialization

Page No: 83

cin>>score;
}
void putscore()
{
cout<<"\n\tSports Score is:"<<score;
}
};
class result:public test,public sports
{
int total;
public:
void display()
{
total=part1+part2+score;
putnumber();
putmarks();
putscore();
cout<<"\n\tTotal Score:"<<total;
}
};
void main()
{
result obj;
clrscr();
obj.getnumber();
obj.getmarks();
obj.getscore();
obj.display();
getch();
}
Output:
Enter Roll No: 200
Enter Marks
Part1: 90
Part2: 80
Enter Sports Score: 80

Roll No: 200


Marks Obtained
Part1: 90
Part2: 80

Developed by: Atish Jain


Intelligents are not born, they are made

d a t
Page No: 84

a p r o

Computer specialization
Sports Score is: 80
Total Score is: 250

/*virtual class*/
class PoweredDevice
{
public:
PoweredDevice(int nPower)
{
cout << "PoweredDevice: " << nPower << endl;
}
};
class Scanner: virtual public PoweredDevice
{
public:
Scanner(int nScanner, int nPower)
: PoweredDevice(nPower)
{
cout << "Scanner: " << nScanner << endl;
}
};
class Printer: virtual public PoweredDevice
{
public:
Printer(int nPrinter, int nPower)
: PoweredDevice(nPower)
{
cout << "Printer: " << nPrinter << endl;
}
};
class Copier: public Scanner, public Printer
{
public:
Copier(int nScanner, int nPrinter, int nPower)
: Scanner(nScanner, nPower), Printer(nPrinter, nPower),
PoweredDevice(nPower)
{
}
};
int main()
{
clrscr();
Copier cCopier(1, 2, 3);

Developed by: Atish Jain


Intelligents are not born, they are made

d a t
Page No: 85

a p r o

Computer specialization

getch();
}
When a class is made virtual base class, cpp takes necessary care
to see that only one copy of that class is inherited.
Note: The keyword virtual can be used in either order.

Abstract classes:
An abstract class is one that is not used to create objects, it is
designed to act as a base class for inheritance. In previous
examples student class is an abstract class, since it was not
used to create any objects.

Constructors in derived class:


A constructor plays an important role in initializating the
objects. Whenever you define an object to the derived class then
the constructor of the base class is executed first and the
constructor of the derived class executed next.
In case of multiple inheritance the base classes are constructed in
the order in which they appear in the declaration of the derived
class.
// Program name: d:\atish\cpp\classes\cons_der1.cpp
# include <iostream.h>
#include <conio.h>
class test
{
public:
test()
{
cout<<"Base class constructor is called:";
}
};
class sample : public test
{
public:
sample()
{
cout<<"\nDerived class constructor is called:";
}
};
void main()
{
clrscr();

Developed by: Atish Jain


Intelligents are not born, they are made

d a t
Page No: 86

a p r o

Computer specialization

sample s;
getch();
}

// constructors in derived class


//Program name: d:\atish\cpp\classes\cons_der.cpp
# include <iostream.h>
# include <conio.h>
class test
{
private:
int a;
public:
test(int x)
{
a=x;
cout<<"A is:"<<a;
}
};
class sample : public test
{
private:
int b;
public:
sample(int x,int y):test(x)
{
b=y;
cout<<"\nB is:"<<y;
}
};
void main()
{
clrscr();
sample one(10,20);
getch();
}
The derived class takes the responsibility of supplying the initial
values to its base classes. Cpp supports the special argument
passing mechanism for that situation. The constructor of the
derived class receives the entire list of values as its arguments
and passes them to the base class constructor in the order in which
they are declared in the class.

Developed by: Atish Jain


Intelligents are not born, they are made

d a t
Page No: 87

a p r o

Computer specialization

Format:Part 1
part 2
Derived class constructor(args) : initialization section
{
(Base class constructor)
----}
The first part provides the declaration of the total arguments that
are passed to the derived constructor. The second part calls the
base class constructor.

Operator overloading:
This concept is one of the main features of the cpp language. This
mechanism gives a special meaning to the operator. To define an
additional task to the operator we must specify what it means in
relation to class to which the operator is applied. This is
possible by using a special function called operator function.

In this we give extra work to built in operator to perform


calculations on class objects here a single operator can perform
difference calculations on different datatype.
We canot overloaded following 3 operators
?: ternary operator
:: scope operator
: inheritance operator
Commonly overloaded operator:
=
+,-,*,/
+=, -=, *=, /=
==,!=
<<,>>
In normal way values are calculated by primitive data types:
Int rel=sum(20,30);
Int rel=sum(obj1,obj2);
Int I,j,k;
I=20,j=30,k=i+j;
//normal function and calculation
//object operation
Int rel=obj1+obj2;
+ operation on object so we have to do operator overloading

Developed by: Atish Jain


Intelligents are not born, they are made

d a t
Page No: 88

a p r o

Computer specialization

Operator overloading can be done with the help of


1. Simple function
2. Friend function
Here operator overloading is 2 catogiorius to operform
1. Unary operator (obj++)
2. Binary operator(if more than 1 object
is involed then it is binary)
Obj3=obj1+obj2;
Syntax:<return type> <class name> :: operator op(arg)
{
--}

/*operator overloading*/
#include<iostream.h>
#include<conio.h>
class student
{
int sub1;
int sub2;
public:
student()
{
sub1=sub2=0;
}
void setdata(int sub1,int sub2)
{
this->sub1=sub1;
this->sub2=sub2;
}
void display()
{
cout<<"\n sub1="<<sub1;
cout<<"\n sub2="<<sub2;
}
//void is for we dont return any value
//++ the sign of the operator which we want to overload
//bez obj1 only one object so we dont want to pass any arguments
void operator ++()
// this is for
obj1++;

Developed by: Atish Jain


Intelligents are not born, they are made

d a t
Page No: 89

a p r o

Computer specialization

{
sub1=sub1+5;//sub1==obj1.sub1
sub2=sub2+5;
}
void operator ++(int temp)
++obj1;
{
sub1=sub1+7;//sub1==obj1.sub1
sub2=sub2+7;
};

// this is for

};
void main()
{
clrscr();
student obj1;
obj1.setdata(5,5);
obj1.display();
obj1++;
obj1.display();
++obj1;
obj1.display();
getch();
}
Similarly we can do the:
Obj--;
--obj;
/*program to overload ++as pstfix operator*/
#include<iostream.h>
#include<conio.h>
class data
{
int a,b,c;
public:
void setdata(int x,int y,int z)
{
a=x;
b=y;
c=z;
}
void showdata()
{
cout<<a<<" "<<b<<" "<<c<<endl;
}
void operator ++(int x)
{

Developed by: Atish Jain


Intelligents are not born, they are made

d a t

a p r o

Computer specialization

Page No: 90
x=5;
a=a+x;
b=b+x;
c=c/x;
}
};
void main()
{
clrscr();
data d;
d.setdata(10,20,30);
d.showdata();
d++;
d.showdata();
getch();
}

Binary operator overloading:


#include<iostream.h>
#include<conio.h>
class student
{
int sub1;
int sub2;
public:
student()
{
sub1=sub2=0;
}
void setdata(int sub1,int sub2)
{
this->sub1=sub1;
this->sub2=sub2;
}
void display()
{
cout<<"\n sub1="<<sub1;
cout<<"\n sub2="<<sub2;
}
student operator+(student tobj2)
{
student temp;
temp.sub1=sub1+tobj2.sub1;
//sub1==obj1.sub1
;

Developed by: Atish Jain


Intelligents are not born, they are made

d a t

a p r o

Computer specialization

Page No: 91

temp.sub2=sub2+tobj2.sub2;
return temp;
}
};
void main()
{
clrscr();
student obj1,obj2,obj3;
obj1.setdata(5,5);
obj2.setdata(10,10);
obj3=obj1+obj2;
obj3.display();
getch();
}
Similarly we can do the:
Obj3=obj1-obj2;
Obj3=obj1*obj2;
Obj3=obj1/obj2;
Obj3=obj1%obj2;

/*obj1=obj1+1000*/
#include<iostream.h>
#include<conio.h>
class student
{
int sub1;
int sub2;
public:
student()
{
sub1=sub2=0;
}
void setdata(int sub1,int sub2)
{
this->sub1=sub1;
this->sub2=sub2;
}
void display()
{
cout<<"\n sub1="<<sub1;
cout<<"\n sub2="<<sub2;
}
student operator+(int value)
{

Developed by: Atish Jain


Intelligents are not born, they are made

d a t
Page No: 92

a p r o

Computer specialization

student temp;
temp.sub1=sub1+value;
temp.sub2=sub2+value;
return temp;
}
};
void main()
{
clrscr();
student obj1,obj2,obj3;
obj1.setdata(5,5);
obj1=obj1+1000;
obj1.display();
getch();
}
/*obj1=100+obj1*/
Now this has some problem because before the operator we are having
built in type integer so integer cant call class function so we
have to use the friend function.
#include<iostream.h>
#include<conio.h>
class student
{
int sub1;
int sub2;
public:
student()
{
sub1=sub2=0;
}
void setdata(int sub1,int sub2)
{
this->sub1=sub1;
this->sub2=sub2;
}
void display()
{
cout<<"\n sub1="<<sub1;
cout<<"\n sub2="<<sub2;
}
friend student operator+(int value,student tobj1);
};
student operator +(int value,student tobj)

Developed by: Atish Jain


Intelligents are not born, they are made

d a t

a p r o

Computer specialization

Page No: 93

{
student temp;
temp.sub1=tobj.sub1+value;
temp.sub2=tobj.sub2+value;
return temp;
}
void main()
{
clrscr();
student obj1;
obj1.setdata(5,5);
obj1=100+obj1;
obj1.display();
getch();
}
/*int rel=obj1==obj2*/
#include<iostream.h>
#include<conio.h>
class student
{
int sub1;
int sub2;
public:
student()
{
sub1=sub2=0;
}
void setdata(int sub1,int sub2)
{
this->sub1=sub1;
this->sub2=sub2;
}
void display()
{
cout<<"\n sub1="<<sub1;
cout<<"\n sub2="<<sub2;
}
int operator==(student tobj)
{
if(sub1==tobj.sub1)
{
return 1;
}
else

Developed by: Atish Jain


Intelligents are not born, they are made

d a t
Page No: 94

a p r o

Computer specialization

{
return 0;
}
}
};
void main()
{
int r;
clrscr();
student obj1,obj2;
obj1.setdata(5,5);
obj2.setdata(5,5);
r=obj1==obj2;
if(r==1)
{
cout<<"both are same";
}
else
{
cout<<"both are not same";
}
getch();
}

/*program to overload equal to operator*/


#include<iostream.h>
#include<conio.h>
class abc
{
int a,b,c;
public:
abc()
{
cout<<"default "<<endl;
a=b=c=5;
}
abc(int x,int y,int z)
{
cout<<"parameterised "<<endl;
a=x;
b=y;
c=z;

Developed by: Atish Jain


Intelligents are not born, they are made

d a t
Page No: 95

a p r o

Computer specialization

}
abc(abc &p)
{
cout<<"copy "<<endl;
a=p.a;
b=p.b;
c=p.c;
}
void show()
{
cout<<a<<" "<<b<<" "<<c<<endl;
}
void operator =(abc &p)
{
cout<<"operator "<<endl;
a=p.a+2;
b=p.b+2;
c=p.c+2;
}
};
void main()
{
clrscr();
abc k(11,22,33);
abc j=k;
abc h;
h.show();
h=k;
k.show();
j.show();
h.show();
getch();
}
/*overload ++ as preincrement*/
#include<iostream.h>
#include<conio.h>
class number
{
int a,b;
public:
void getdata()
{
cout<<"enter 2 no's";
cin>>a>>b;
}
void showdata()

Developed by: Atish Jain


Intelligents are not born, they are made

d a t
Page No: 96

a p r o

Computer specialization

{
cout<<a<<" "<<b<<endl;
}
void operator ++()
{
a=a+2;
b=b-2;
}
};
void main()
{
clrscr();
number p;
p.getdata();
p.showdata();
++p;
p.showdata();
++p;
p.showdata();
getch();
}
/*program to overload < operator*/
#include<iostream.h>
#include<conio.h>
class marks
{
int m,p,c;
public:
void getmar()
{
cout<<"enter 3 marks";
cin>>m>>p>>c;
}
void showmar()
{
cout<<m<<" "<<p<<" "<<c<<endl;
}
int operator <(marks &q)
{
int t1,t2;
t1=m+p+c;
t2=q.m+q.p+q.c;
if(t1<t2)
return 1;
else

Developed by: Atish Jain


Intelligents are not born, they are made

d a t

a p r o

Computer specialization

Page No: 97
return 0;
}
};
void main()
{
marks x,y;
clrscr();
x.getmar();
y.getmar();
if(x<y)
x.showmar();
else
y.showmar();
getch();
}

#include <iostream.h>
class temp
{
private:
int count;
public:
temp():count(5){ }
/*TEMP()
{
COUNT=5;
}*/
void operator ++() {
count=count+1;
}
void Display() { cout<<"Count: "<<count; }
};
int main()
{
temp t;
++t;
/* operator function void operator ++() is called
*/
t.Display();
return 0;
}
#include<iostream.h>
#include<conio.h>
class complex
{
int a,b;

Developed by: Atish Jain


Intelligents are not born, they are made

d a t

a p r o

Computer specialization

Page No: 98
public:

void getvalue()
{
cout<<"Enter the value of Complex Numbers a,b:";
cin>>a>>b;
}
complex operator+(complex ob)
{
complex t;
t.a=a+ob.a;
t.b=b+ob.b;
return(t);
}
complex operator-(complex ob)
{
complex t;
t.a=a-ob.a;
t.b=b-ob.b;
return(t);
}
void display()
{
cout<<a<<"+"<<b<<"i"<<"\n";
}
};

void main()
{
clrscr();
complex obj1,obj2,result,result1;
obj1.getvalue();
obj2.getvalue();
result = obj1+obj2;
result1=obj1-obj2;
cout<<"Input Values:\n";
obj1.display();
obj2.display();
cout<<"Result:";
result.display();
result1.display();

Developed by: Atish Jain


Intelligents are not born, they are made

d a t
Page No: 99

a p r o

Computer specialization

getch();
}
op is the operator being overloaded. It must be prefix with the
keyword operator. Operator function must be either member function
or friend function, it should be defined at public section. When an
operator is overloaded its original meaning is not changed.
// Overloading unary operator // Program name : d:\atish\cpp\classes\op_unary.cpp
# include <iostream.h>
# include <conio.h>
class test
{
private:
int x,y,z;
public:
void getdata(int a,int b,int c)
{
x=a;
y=b;
z=c;
}
void dispdata()
{
cout<<"X = "<<x<<endl;
cout<<"Y = "<<y<<endl;
cout<<"Z = "<<z;
}
void operator -(); // function declaration
};
void test :: operator -()
{
x=-x;
y=-y;
z=-z;
}
void main()
{
clrscr();
test s;
s.getdata(10,-20,30);
- s;
s.dispdata();
getch();
}
// Overloading unary operator - ++

Developed by: Atish Jain


Intelligents are not born, they are made

d a t
Page No: 100

a p r o

Computer specialization

// Program name: d:\atish\cpp\classes\op_pinc.cpp


# include <iostream.h>
# include <conio.h>
class test
{
private:
int x,y,z;
public:
void getdata(int a,int b,int c)
{
x=a;
y=b;
z=c;
}
void dispdata()
{
cout<<"X = "<<x<<endl;
cout<<"Y = "<<y<<endl;
cout<<"Z = "<<z;
}
void operator ++();
};
void test :: operator ++()
{
++x;
++y;
++z;
}
void main()
{
clrscr();
test s;
s.getdata(10,20,30);
++s;
s.dispdata();
getch();
}
// Overloading binary operator +
// program name: d:\atish\cpp\classes\op_plus.cpp
# include <iostream.h>
# include <conio.h>
class sample
{
private:
int no;
public:

Developed by: Atish Jain


Intelligents are not born, they are made

d a t
Page No: 101

a p r o

Computer specialization

void store()
{
cout<<"Enter a no:";
cin>>no;
}
void display();
sample operator+(sample);
};
sample sample :: operator+(sample b)
{
sample temp;
temp.no=no+b.no;
return(temp);
}
void sample ::display()
{
cout<<"The result is:"<<no;
}
void main()
{
clrscr();
sample a,b,c;
a.store();
b.store();
c=a+b;
// invokes the operator function
// c=a.operator+(b);
c.display();
getch();
}

// Adding of two strings


// Program name: d:\atish\cpp\classes\op_addst.cpp
# include <iostream.h>
# include <conio.h>
class test
{
private:
char str[20];
public:
void store()

Developed by: Atish Jain


Intelligents are not born, they are made

d a t

a p r o

Computer specialization

Page No: 102


{

cout<<"Enter a string:";
cin>>str;
}
void disp();
test operator+(test); // func... decl..
};
test test :: operator+(test a)
{
test temp;
for (int i=0;str[i]!='\0';i++)
temp.str[i]=str[i];
temp.str[i++]=' ';
for(int j=0;a.str[j]!='\0';j++,i++)
temp.str[i]=a.str[j];
temp.str[i]='\0';
return(temp);
}
void test :: disp()
{
cout<<"The string is:"<<str;
}
void main()
{
clrscr();
test x,y,z;
x.store();
y.store();
z=x+y;
z.disp();
getch();
}
// Overloading greater than operator >
// Program name d:\atish\cpp\classes\op_grea.cpp
# include <iostream.h>
# include <conio.h>
class sample
{
private:
int no;
public:

Developed by: Atish Jain


Intelligents are not born, they are made

d a t
Page No: 103

a p r o

Computer specialization

void store()
{
cout<<"Enter a no:";
cin>>no;
}
void display();
int operator>(sample);
};
int sample :: operator>(sample x)
{
if (no>x.no)
return(1);
else
return(0);
}
void main()
{
clrscr();
sample s1,s2;
s1.store();
s2.store();
if (s1>s2)
cout<<"S1 is big";
else
cout<<"S2 is big";
getch();
}
// Write a program to overload comparison operator (==) to compare
two strings.

Pointers:
Pointer is a variable that can contains address of another
variable.
Use of pointers:
Call by reference.
Accessing array elements.
Obtaining memory at run time.
Creating data structures( Linked lists, stacks, ).
Virtual functions.

Developed by: Atish Jain


Intelligents are not born, they are made

d a t

a p r o

Computer specialization

Page No: 104

Program to demonstrate pointers:


# include <iostream.h>
# include <conio.h>
void main()
{
int no=10,*p;
clrscr();
p=&no;
cout<<"\nValue of no:"<<no;
cout<<"\nAddress of no:"<<&no;
cout<<"\nVaule of p:"<<p;
cout<<"\nValue at p:"<<*p;
getch();
}

Adding of 2 nos using pointers.


Passing array to a function.
Passing string to a function.

Dynamic memory allocation using new and delete operators:

In arrays memory is allocated at compile time, we should know


the size of the memory in advance, which wastes lot of memory.
Dynamic memory allocation means allocating memory at run time.
New operator:
used to allocate the memory.
Syntax:
<data type> <variable>;
<variable> = new <data type>;
Ex:
int *p;
p= new int;
Allocates 2 bytes of memory and assigns the first byte to p.
delete operator:
used to release the memory.
Syntax:
delete <pointer variable>;
ex:
delete p;

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

Developed by: Atish Jain


Intelligents are not born, they are made

d a t
Page No: 105

a p r o

Computer specialization

class country
{
char name[10];
float pop;
int year;
public:
country()
{
cout<<"constructor"<<endl;
}
~country()
{
cout<<name<<" destractor "<<endl;
}
void getc()
{
cout<<"enter country name population year";
cin>>name>>pop>>year;
}
void show()
{
cout<<name<<" has "<<pop<<" population "<<endl;
cout<<"it got freedom in "<<year<<endl;
}
};
void main()
{
country *c;
clrscr();
cout<<"size="<<sizeof(c)<<"pointer="<<c<<endl;
c=new country();
cout<<"size:"<<sizeof(c)<<"pointer="<<c<<endl;
c->getc();
c->show();
delete c;
cout<<" size: "<<sizeof(c)<<"pointer="<<c<<endl;
getch();
}

Polymorphism:
Polymorphism means one name multiple forms, implemented through
overloaded functions.
Polymorphism is two types:
static/early binding(linking).
Dynamic/late binding(linked).

Developed by: Atish Jain


Intelligents are not born, they are made

d a t

a p r o

Computer specialization

Page No: 106

static/early binding(linking):
Function which is to be executed is selected at the time of
compilation, which is also known as compile time polymorphism.
Example:
class A
{
int x;
public:
void show();
};
class B: public A
{
int y;
public:
void show();
};
Since the show() function is not overloaded therefore static
binding does not take place, compiler does not know what to do.
So the linking takes place when the function is called using the
class object.
This is achieved in c++ using a mechanism known as virtual
functions. ie virtual functions supports run time polymorphism.

Assigning derived class object address to base pointer is known as


upcasting.
Example:
# include <iostream.h>
# include <conio.h>
class Base
{
public:
void display()
{
cout<<"\nBase class display function..";
}
void show()
{
cout<<"\nBase class show function..";

Developed by: Atish Jain


Intelligents are not born, they are made

d a t
Page No: 107

a p r o

Computer specialization

}
};// end of base class
class Derived : public Base
{
public:
void display()
{
cout<<"Derived class display function..";
}
void show()
{
cout<<"Derived class show function..";
}
};// end of derived class
void main()
{
Base b;
Derived d;
Base *p;
cout<<"Pointer variable p points to base class..\n";
p=&b;
p->display();
p->show();
cout<<"Pointer variaeble p points to derived class...\n";
p=&d;
p->display();
p->show();
getch();
}
Pure virtual functions:
A pure virtual function is virtual function with no body. Often
the virtual functions of the base class are not used.
Abstract class:
A class that has atleast one pure virtual function is called as
abstract class.
Real life example:
# include <iostream.h>
# include <conio.h>
class Media
{
protected:

Developed by: Atish Jain


Intelligents are not born, they are made

d a t
Page No: 108

a p r o

Computer specialization

char title[50];
float price;
public:
Media(char *s,float a)
{
strcpy(title,s);
price=a;
}
virtual void display(){}; // empty virtual function
};
class Book: public Media
{
int pages;
public:
Book(char *s,float a,int p):Media(s,a)
{
pages=p;
}
void display();
};
class Tape: public Media
{
float time;
public:
Tape(char *s, float a, float t):Media(s,a)
{
time=t;
}
void display();
};
void Book :: display()
{
cout<<"\n Title: "<<title;
cout<<"\n Pages: "<<pages;
cout<<"\n Price: "<<price;
}
void Tape :: display()
{
cout<<"\n Title: "<<title;
cout<<"\n Play time: "<<time<<" mins..";
cout<<"\n Price: "<<price;
}
void main()
{

Developed by: Atish Jain


Intelligents are not born, they are made

d a t

a p r o

Computer specialization

Page No: 109

char *title=new char[30];


float price,time;
int pages;
//Book details
cout<<"\Enter book details..";
cout<<"Title : "; cin>>title;
cout<<"Price : "; cin>>price;
cout<<"Pages : "; cin>>pages;
Book b1(title,price,pages);
//Tape details
cout<<"Enter tape details...";
cout<<"Title : "; cin>>title;
cout<<"Price : "; cin>>price;
cout<<"Pay time(mins) : "; cin>>time;
Tape t1(title,price,time);
Media *list[2];
list[0]=&b1;
list[1]=&t1;
cout<<"Media details...";
cout<<"\n............Book........";
list[0]->display();
cout<<"\n...........Tape........";
list[1]->display();
getch();
}
Files:
Many real life problems handle large volumes of data and, in
such situations, we need to use some devices such as floppy disk
or hard disk to store the data. The data is stored in these
devices using the concept of files.
A file is a collection of data stored in a particular area on
the disk.
Programs can be developed to perform the read and write
operations on these files.
A program involves the following tasks:
* Data transfer between the console unit and the program.
* Data transfer between the program and a disk file.

Developed by: Atish Jain


Intelligents are not born, they are made

d a t
Page No: 110

a p r o

Computer specialization

External Memory
Data Files

Write Data
(to files)

Program file
interaction
Read Data
(from files)

Internal Memory
Program+Data
cout <<
(put data to
screen)

cin >>
(Get data
from
keyboard)

Console
Program
interaction

Introduction to Streams:
cout and cin in c++ are nothing but streams. A stream is a source or
destination for collection of characters(strings).
There are two types of streams:
Output streams: - which allows to write or store
characters(insertion).
Input streams: - which allow to read or fetch characters(Extraction).

ios

istream

ostream

ifstream

ofstream
iostream

Developed by: Atish Jain


Intelligents are not born, they are made

d a t

a p r o

Computer specialization

Page No: 111

Graphical representation of input and output streams:

Read Data

Input stream

Disk File
Write Data

Data Input

Program
Data output
Output stream

Text and binary files


The C++ language supports two types of files:

Text files

Binary files
By default, C++ opens the files in text mode.
Ofstream <variable> file creations with streams
Ifstream <variable> getting data from file already saved file
Fstream <variable>
<variable>.open for open a file
<variable>.close for close a file after using
<variable> << with this write a content in file and also
retrieve content from file
Working with single file:
# include <iostream.h>
# include <fstream.h>
# include <conio.h>
void main()
{
char name[20];
int cost;
ofstream outf("ITEM"); // opening file with constructor

Developed by: Atish Jain


Intelligents are not born, they are made

d a t

a p r o

Computer specialization

Page No: 112

cout<<"Enter item name:";


cin>>name;
outf<<name<<"\n";
cout<<"Enter item cost:";
cin>>cost;
outf<<cost<<"\n";
outf.close();
ifstream inf("ITEM");
inf>>name;
inf>>cost;
cout<<"\nItem details.."<<endl;
cout<<"Name : "<<name<<endl;
cout<<"Cost : "<<cost<<endl;
inf.close();
getch();
}
Caution:
When a file is opened for writing only, a new file is created
if there is no file of that.
If a file exists with that name, then its contents are deleted
and a new file is opened with that name.

Opening files:
The function open() is used to open multiple files with the same
stream object.
ofstream outfile;
outfile.open(file 1);
outfile.close();
outfile.open(file 2);
outfile.close();
Working with multiple files:
# include <iostream.h>
# include <fstream.h>
# include <conio.h>

Developed by: Atish Jain


Intelligents are not born, they are made

d a t

a p r o

Computer specialization

Page No: 113

void main()
{
ofstream fout;
fout.open("country");
fout<<"India"<<"\n";
fout<<"America"<<"\n";
fout<<"Japan"<<"\n";
fout.close();
fout.open("cities");
fout<<"Rajahmundry"<<"\n";
fout<<"Hyderabad"<<"\n";
fout<<"Mumbai"<<"\n";
fout.close();

//Reading data from files


char str[80];
int no=80;
ifstream fin;
fin.open("country");
cout<<"Contents of country..\n";
while(fin) // checks for end of file
{
fin.getline(str,no);
cout<<str<<"\n";
}
fin.close();

fin.open("cities");
cout<<"\n\nContents of cities...\n";
while(fin) // checks for end of file
{
fin.getline(str,no);

Developed by: Atish Jain


Intelligents are not born, they are made

d a t

a p r o

Computer specialization

Page No: 114


cout<<str<<"\n";
}
fin.close();
getch();
}

/*entering data by using input output stream in appended mode*/


#include<iostream.h>
#include<conio.h>
#include<fstream.h>
void main()
{
fstream fp;
clrscr();
fp.open("myfile",ios::app);
char str[30];
cout<<"enter content:";
cin.getline(str,20);
fp<<str;
cout<<"file appended";
getch();
}
/*creating and open a file by usinf fstreams*/
#include<iostream.h>
#include<conio.h>
#include<fstream.h>
void main()
{
fstream fp;
char s[30];
clrscr();
fp.open("myfile",ios::out);
fp<<"another file";
cout<<"another file";
cout<<"enter string";
cin.getline(s,30,'$');
cin.ignore();
fp.write(s,30);
fp.close();
fp.open("myfile",ios::in);
fp.getline(s,30);
cout.write(s,30);
cout<<"\n end";
getch();

Developed by: Atish Jain


Intelligents are not born, they are made

d a t

a p r o

Computer specialization

Page No: 115


}

Templates:
Templates is one of the features added to c++ recently. It is a new
concept which enables us to define generic classes and functions,
which are used to develop generic programming.
Generic programming is an approach where generic types are used as
parameters in programs so that they work for a variety of suitable
data types and data structures.
Function template:
Syntax:
template <class T>
return type function name(arguments of type T)
{
------}
Example:
# include <iostream.h>
# include <conio.h>
template <class T>
void swap(T &x,T &y)
{
T temp=x;
x=y;
y=temp;
}
void main()
{
int a,b;
float x,y;
cout<<"Enter two no's:(integers)..:";
cin>>a>>b;
swap(a,b);
cout<<"\nA is:"<<a;
cout<<"\nB is:"<<b;
cout<<"\n\nEnter two no's:(floats)..:";
cin>>x>>y;
swap(x,y);
cout<<"\nX is:"<<x;
cout<<"\nY is:"<<y;

Developed by: Atish Jain


Intelligents are not born, they are made

d a t
Page No: 116

a p r o

Computer specialization

getch();
}
Function templates with multiple parameters:
Syntax:
template <class T1,class T2>
return type function name(arguments of type T1,T2)
{
------}
Example:
# include <iostream.h>
# include <conio.h>
template <class T1,class T2>
void display(T1 x,T2 y)
{
cout<<x<<" "<<y<<"\n";
}
void main()
{
display(500,"datapro");
display(25.32,"Hello");
getch();
}
class templates:
# include <iostream.h>
# include <conio.h>
template <class T>
class xyz
{
T no;
public:
void store()
{
cout<<"\n\nEnter a data item...:";
cin>>no;

Developed by: Atish Jain


Intelligents are not born, they are made

d a t

a p r o

Computer specialization

Page No: 117


}

void disp()
{
cout<<"The data is:"<<no;
}
};
void main()
{
clrscr();
xyz <int> x;
x.store();
x.disp();
xyz <float> y;
y.store();
y.disp();
xyz <char> z;
z.store();
z.disp();
getch();
}
/*template predations with sizeof key word*/
#include<iostream.h>
#include<conio.h>
template<class A,class B>
void show(A p,B q)
{
cout<<sizeof(p)<<"\t"<<sizeof(q)<<endl;
cout<<"p="<<p<<"\tq="<<q<<endl;
}
void main()
{
clrscr();
show(10,20);
show(20,'r');
show("hello",36.12);
getch();
}
This operator:

Developed by: Atish Jain


Intelligents are not born, they are made

d a t

a p r o

Computer specialization

Page No: 118

It is a special pointer which store address of current


object(active )we use this for access variables and address of
current object at current time.
/*address of object and this key word printing*/
#include<iostream.h>
#include<conio.h>
class test
{
public:
void fun()
{
cout<<this<<endl;
}
};
void main()
{
test t;
clrscr();
t.fun();
cout<<&t;
getch();
}
/*program for this pointer*/
#include<iostream.h>
#include<conio.h>
class test
{
int no;
public:
test()
{
no=25;
}
void setdata(int no)
{
this->no=no;
}
void showdata()
{
cout<<"no="<<no<<endl;
}
};
void main()

Developed by: Atish Jain


Intelligents are not born, they are made

d a t

a p r o

Computer specialization

Page No: 119


{
test t;
clrscr();
t.showdata();
t.setdata(10);
t.showdata();
getch();
}

keywords:
asm
auto
bool *
break
case
catch
char
class

const
const_cast *
continue
default
delete
do
double
dynamic_cast
*

else
enum
explicit
*
export
*
extern
false *
float
for

friend
goto
if
inline
int
long
mutable *
namespace
*

new
operator
private
protected
public
register
reinterpret_cast
*
return

short
signed
sizeof
static
static_cast
*
struct
switch
template

this
throw
true *
try
typedef
typeid *
typename
*
union

unsigned
using *
virtual
void
volatile
wchar_t *
while

Developed by: Atish Jain


Intelligents are not born, they are made

Anda mungkin juga menyukai