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
d a t
Page No: 2
a p r o
Computer specialization
DATA
Functions operating
On that data
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.
d a t
Page No: 3
a p r o
Computer specialization
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.
d a t
a p r o
Computer specialization
Page No: 5
User defined
Structures
Unions
Classes
Enumerations
Predefined
Integral
type
Derived
Floating
type
Arrays
Functions
Pointers
Reference
Void
float
int
double
char
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;
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.
// 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
d a t
Page No: 8
a p r o
Computer specialization
# 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();
}
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();
}
d a t
Page No: 10
a p r o
Computer specialization
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;
}
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;
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
d a t
a p r o
Computer specialization
Page No: 14
cout<<"no is "<<no;
getch();
}
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>;
3. for loop
for (expr1;expr2;expr3)
{
stmt1;
stmt2;
}
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);
}
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 >
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);
}
d a t
Page No: 17
a p r o
Computer specialization
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()
{
d a t
Page No: 18
a p r o
Computer specialization
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)
{
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;
d a t
a p r o
Computer specialization
Page No: 21
z=x+y;
cout<<The result is:<<z;
}
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
{
}
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
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.
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>
d a t
Page No: 24
a p r o
Computer specialization
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);
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>
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;
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.
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;
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();
}
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)
d a t
a p r o
Computer specialization
Page No: 31
{
return(x+y);
}
Classes and objects:
datamembers;
member functions;
};
No Entry to private
area for out side
members.
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.
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()
{
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)
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.
d a t
a p r o
Computer specialization
Page No: 36
d a t
a p r o
Computer specialization
Page No: 37
}
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
d a t
Page No: 39
a p r o
Computer specialization
d a t
a p r o
Computer specialization
Page No: 40
{
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;
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
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;
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
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()
{
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
getch();
}
Output:
d a t
a p r o
Computer specialization
Page No: 46
a value:3
a value:3
a value:3
d a t
Computer specialization
Page No: 47
a p r o
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.
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();
}
d a t
a p r o
Computer specialization
Page No: 49
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;
}
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";
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();
d a t
Page No: 52
a p r o
Computer specialization
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).
d a t
Page No: 53
a p r o
Computer specialization
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:
d a t
a p r o
Computer specialization
Page No: 55
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
{
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
{
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
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;
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
{
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:";
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.
Types of inheritance:
1. Single inheritance
3. Multilevel inheritance
A
Base class
Derived class
2. Multiple inheritance
A
4. Hierarchical inheritance
A
d a t
a p r o
Computer specialization
Page No: 63
P
riva
te
Public
Private
Public
Public
P
ubli
c
Private
Public
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()
{
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
d a t
a p r o
Computer specialization
Page No: 66
private
protected
public
private
protected
public
P
U
B
L
I
C
protected
public
private
protected
public
Public derivation
Private
Not inherited
Protected
Protected
Public
Public
2. Multiple inheritance:
Private derivation
Not inherited
Private
Private
Protected derivation
Not inherited
Protected
Protected
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;
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()
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()
d a t
a p r o
Computer specialization
Page No: 70
{
cout<<"Maths:"<<m<<endl;
cout<<"Physics:"<<p<<endl;
cout<<"Chemistry:"<<c<<endl;
}
};
BANK
# include <iostream.h>
# include <conio.h>
class bank
{
protected:
int accno;
char name[20];
Accno
Name
bal
Getdet()
Dispdet()
DEPOSIT
WITHDRAWL
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();
}
};
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
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;
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;
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()
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";
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;
d a t
Page No: 78
a p r o
Computer specialization
p=&c;
p->getcomp();
p->showcomp();
c.getcomp();
c.showcomp();
getch();
}
}
#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;
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;
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();
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();
}
rno, name
STUDENT
rno, name
rno, name
MARKS
SPORTS
rno, name
rno, name
RESULT
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:";
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
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);
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.
d a t
Page No: 86
a p r o
Computer specialization
sample s;
getch();
}
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.
d a t
Page No: 88
a p r o
Computer specialization
/*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++;
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)
{
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();
}
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)
{
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)
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
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();
}
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()
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
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;
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();
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 - ++
d a t
Page No: 100
a p r o
Computer specialization
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();
}
d a t
a p r o
Computer specialization
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:
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.
d a t
a p r o
Computer specialization
#include<iostream.h>
#include<conio.h>
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).
d a t
a p r o
Computer specialization
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.
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:
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()
{
d a t
a p r o
Computer specialization
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
d a t
a p r o
Computer specialization
Read Data
Input stream
Disk File
Write Data
Data Input
Program
Data output
Output stream
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
d a t
a p r o
Computer specialization
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>
d a t
a p r o
Computer specialization
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();
fin.open("cities");
cout<<"\n\nContents of cities...\n";
while(fin) // checks for end of file
{
fin.getline(str,no);
d a t
a p r o
Computer specialization
d a t
a p r o
Computer specialization
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;
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;
d a t
a p r o
Computer specialization
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:
d a t
a p r o
Computer specialization
d a t
a p r o
Computer specialization
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