0% found this document useful (0 votes)
6 views

Sev C++ All

Sev C++ All

Uploaded by

pandi1985
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Sev C++ All

Sev C++ All

Uploaded by

pandi1985
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 258

Programming in C++

Prepared by.,

Dr.N.Sevugapandi., MCA., M.Phil.,Ph.D.,


Guest Lecturer of Computer Science(UG&PG),
Government Arts and Science College,
Kovilpatti - 628 503. Thoothukudi District .
Mobile: 9600412482.
E-Mail: [email protected]

1
2
Software Crisis

3
4
Software Evaluation

5
6
7
8
All around us in the
real world are
objects.
Each object has
certain
characteristics and
exhibits certain
behaviour 9
10
OBJECT
Data
Color : Black
Year : 2008
Actions
Start
Stop
Accelerate
11
The Object-Oriented
Approach - III

Accounts Sales
Personnel

The real world around is full of objects .We can consider both living
beings as well as things as objects.For example,the different
departments in a company are objects.
12
Why OOP’s Concept are Used?
The drawbacks of Traditional Programming
approach are

Unmanageable Programs

Code Reusability not Optimum

Problems in Modification of Data

Difficulty in Implementation
13
Object – Oriented Programming
Here the application has to implement the entities as they are
seen in real life and associate actions and attributes with each.

Data Functions
Employee details Calculate salary
Salary statements Pay salary
Accounts
Bills Pay bills
Vouchers Tally accounts
Reciepts Transact with banks
14
Benefits of Object Oriented Programming approach
are -
 OOP offers better implementation

 OOP offers better data security


 OOP offers better code reusability
 OOP offers more flexibility
 OOP offers better manageable programs
 Large complexity in the software development
can be easily managed
 User defined datatypes can be easily constructed
15
Object Oriented Approach

Problem
Identification Analysis

Maintenance Design

Implementation Development

Testing
16
 Data acquisition Systems

 Client/Server Computing

 Object –Oriented Database applications

 Artificial Intelligence and expert systems

 systems such as process control, temperature control etc.

 GUI based system such as Windows Applications

 Computer Aided Design and manufacturing Systems

17
Encapsulation
Data Abstraction
Inheritance
Polymorphism
Class 18
Grouping of data and methods into a
single entity is known as Data
Encapsulation

It is a technical name for


information hiding. (i.e data hiding or
data security)
19
Encapsulation

Class

Not accessible from Private


outside class

Accessible from outside Public


class

20
Data abstraction enhances security as use
of data is restricted to certain functions
only.
Abstraction is more used where you
want only a certain number of
functions/methods are accessing data. 21
For Example

Class Data abstraction is a process of

identifying properties and

methods related much to a


Attributes particular entity as relevant to the

application

Methods

22
It is the process of
creating a new class from
an existing class

23
Reusability can be achieved through inheritance

Animals

Insects Mammals Reptiles Amphibians

Humans Non-Humans

24
Reusability can be achieved through inheritance

25
Reusability
Programs can be
broken into reusable Shape
objects
Existing classes can be
used with additional
features

26
Benefits of Inheritance

27
• polymorphism allows a programmer to
purse a course of action by sending a
message to an object without concerning
about how the software system is to
implement the action
Simply defined as “Same thing
can behave different ones”
28
Class -
Artiste

Dancer Sculptor Poet

Subclasses
Class : Shape
Methods :
Draw
Move
Initialize
29
30
31
32
A class is what defines all the data
members and the methods that an object
should have.

The class defines the characteristics that


the object will possess; it could also be
referred to as a blueprint of the object.

33
For Example

Polygon Polygon class


objects
Properties
Vertices
Abstract Border Color
Fill Color
into Methods
Draw
Erase
Move

34
Access Specifiers of a Class

Class
Not
accessible
from outside Private
the class
Data or
functions
Public
Accessible
from outside Data or
the class functions

35
Object Oriented Languages

• Some of the leading object oriented


languages are:
– C++
– Smalltalk
– Eiffel
– CLOS
– Java

36
To access the member data
and member function defined
inside the class

37
38
39
Basic Data Types

40
41
42
Scope Resolution Operator

43
44
45
46
Arithmetic Operators
Arithmetic Operators are used to perform numerical
operations
Operator Meaning Example
+ Addition x=10,y=5
x+y -> 21
- Subtraction X-y -> 5
* Multiplication X*y -> 50
/ Division x/y -> 2
% Modulo Division X%y -> 0

47
Relational Operators
Relational operators are used to test the relationship
between two variables or constant

Operator Meaning Example Result value


< Less Than x=10,y=5 False 0
X<y
> Greater Than X>y True 1

<= Less than or Equal X<=y False 0


to

>= Greater than or X>=y True 1


equal to
!= Not Equal to X!=y False 0

== Equal To X==y False 0


48
Logical Operators
Logical operators are used to combine two or more
relational expressions. This operator is used to test more than
one condition at a time.
Operator Meaning Example Result
&& Logical And When x=9, y=5 (x>=5) && (z==‘9’) True
|| Logical Or (X>=6) || (z==‘a’) True
! Logical Not !(x>8) False

Operator Meaning Syntax Example Result


++ Unary Plus Variablename++; (or) X=10; X=11
++ variable name; X++;
-- Unary Variablename--; (or) X=10; X=9
Minus -- variable name; X--; 49
Simple conditional operations can be carried
out with the conditional operator(?:)

Expression1 ? Expression 2:expression 3

Condition True Part False Part

#include<iostream.h>
void main()
{ OUTPUT
int a=10,b=5,c;
The Result is
C=(a>b)?a:b;
cout<<“The Result is“<<c;
10
}

50
The Assignment Operator
In C++, the assignment operator(=) can be used for assigning
a value to a variable

51
Variablename <arithmetic Operator>=Expression;

Simple Assignment Operators Equivalent Shorthand Assignment


Operators
x=x+1 X += 1

y=y-1 Y =- 1
z=z*(x+y) Z *= (x+y)
Y=y/(x+y) Y /= (x+y)
X=x%z X %= z

52
Used in applications which require manipulation of
individual bits within a word of memory
Operators Meaning
~ One’s
Complement
<< Left Shift
>> Right Shift
& Bitwise AND
! Bitwise OR
^ Bitwise X-OR

Operators Meaning Example


, Comma Operator Z=(x=5,y=6,x+y)
53
* Pointer Operator
SCOPE RESOLUTION
OPERATOR ::
Used to define the
member function defined
outside of the class

54
55
Manipulators
Manipulator function are special stream functions that
change
certain characteristics of input and output.
All the manipulator functions prototypes are defined in the

header file <iomanip.h.>


Some Examples are :
 endl (new line character)
 setbase(covert the base value in to another bases value)
 setw( set the width of the output)
 setfill(fills the given character in the unused field)
 setprecision(displays the number of digits after the decimal point in
the floating numbers. 56
setfill(char):it can be used to fills the given character in
the unused field
#include<iostream.h>
#include<iomanip.h>
#include<conio.h>
void main()
{
int a=10,b=20;
clrscr();
cout<<setfill('*');
cout<<setw(5)<<a<<setw(5)<<b<<endl;
cout<<setfill('$');
cout<<setw(7)<<a<<setw(7)<<b<<endl;
getche();
}
57
setw(): it can be used to set the width of
the output field
#include<iostream.h>
#include<iomanip.h>
#include<conio.h>
void main()
{
int a=10,b=20;
clrscr();
cout<<setw(5)<<a<<setw(5)<<b<<endl;
cout<<setw(15)<<a<<setw(15)<<b<<endl;
getche();
}
58
setprecision():This manipulator control display
the number of digits after the decimal point for
the floating numbers

#include<iostream.h>
#include<conio.h>
#include<iomanip.h>
void main()
{
int a=10,b=3;
clrscr();
float c=(float)a/b; //Casting Type
cout<<setprecision(1)<<c<<endl;
cout<<setprecision(2)<<c<<endl;
cout<<setprecision(3)<<c<<endl;
getche();
59
}
//setbase():This manipulator control to convert the base value
in to //another bases value

#include<iostream.h>
#include<conio.h>
#include<iomanip.h>
void main()
{
int num;
clrscr();
cout<<"Enter a Number : ";
cin>>num;
cout<<"Decimal Value : "<<num<<endl;
cout<<"Hexadecimal Value : "<<setbase(16)<<num<<endl;
cout<<"Octal Value : "<<setbase(8)<<num<<endl;
cout<<"Decimal Value : "<<setbase(10)<<num<<endl;
getch();
}
60
 These are special functions that are used with cout
statements for getting formatted outputs
 The ios base class contains member functions like
width(),precision(),file(),setf() and unsetf() to display formatted
output

61
Used to convert one datatype into another data type

#include<iostream.h>
#include<conio.h>
void main()
{
int a=10,b;
float c=2.3;
clrscr();
b=int(a+c);
Cout<<"The value of b is <<b;
getch();
} 62
Type Conversion
This is used to convert one data type to another data type. The automatic type
conversions for evaluating an expression are given below -

For example,

63
Operator Precedence

64
65
66
67
68
69
A Character denotes an alphabet, digit or a special
character. These characters can be combined to form variables.

Lowercase Letters – A,B,C….. Z


Uppercase Letters - a,b,c…… z

Digits – 0,1,2,3,…7,8,9

+ Plus Sign - Minus Sign , Comma

* Asterisk / Slash = Equal to


@ At Symbol < Less Than : Colon
70
; Semicolon
10 4600.5 “A”
‘A’
-356 -0.963 “CSC”
‘*’

71
Variables are named locations in memory that are used to
hold a value that may be modified by the program.

The syntax for declaring a variable is

K5.ico ANIMATAY006.ICO
Data type Variablename;

Valid Examples :
CSC avg_val m1
Chennai Anu mark_1

Some erroneous identifier names are - 1stsst


oh!god
start….end 72
RULES for framing a variable :

The first character in the Variable name must be an alphabet


Alphabets can be followed by a number of digits or
underscores
No commas or Blank spaces are allowed within a variable
name
No Special character other than Underscore(_) can be used in
a variable name.
The variable name should not be a keyword
Variable names are case sensitive
It should not be of length more than 31 characters
73
Escape Sequence
Escape sequences are specified as the first argument in
Output Statement. They are always preceded with a

backslash

74
Preprocessor Directives (Incl. HeaderFile)
Global Variable Declarations;
class<class name>
{
private :
member data;
public :
Member functions;
};
void main(){
Local Variable Declarations;
Input/Output Statements;
}
75
 Preprocessor directives are the instructions given to the
compiler.

 They are not translated into machine language, but are


operated upon directly by the compiler before the
compiling process begins.

 Preprocessor directives begin with a # (hash)

 Preprocessor directives are often placed in the beginning


of a program before the main() is declared.

76
A lot of library functions are
subdivided into number of groups.
This groups are called Header files.

Syntax : #include<headerfilename.h>
Examples: #include<iostream.h>
#include<process.h>
iostream -> Input/Output Stream
Conio -> Console Input/Output
Void -> Keyword. It Means Returns Nothing
main() -> It is a function name which can be
used to indicate the beginning of the program
77
execution
 The comment statements are used in a program
must be started with a pair of slashes (//)

 They are may or may not be present in a program

 It improves the readability of a program

 /* ………… */ Multiple Lines

78
79
Unformatted I/O Statement
Characters can be read and written in C
using the following functions.

80
cin
 It uses the standard input stream cin and the
operator >> for reading the input.
 It is an extraction operator used to take the values
from stream object on its left and places the variable to
its right.
Syntax : cin>>variablename;

Example : cin>>name>>age>>salary;
81
cout
It uses the standard output stream cout and
the operator << for writing the output.
It is an insertion operator used to redirects the
text output to the screen.

Syntax : cout<<“message”<<variablename;

Example : cout<<“The Name is”<<name;


82
cout<<name<<age<<salary;
Input/Output Statement Example
#include<iostream.h>
#include<conio.h>
void main()
{
char s[50];
clrscr();
cout<<"\n Enter Your String :";
cin>>s;
cout<<"\n Your String is "<<s;
getch();
}

83
 C++ provides two pre-defined objects cin and cout for
handling input and output
 The stream extraction operator along with cin statement is
used for reading input
 The stream insertion operator along with cout statement is
used for displaying the output
 The comment statements are used in a program must be
started with a pair of slashes (//)
 The preprocessor directives <#include<iostream.h> refers to a
special file which contains the information about the standard
input and output operations which must be included in the
program when it is compiled 84
cin
cout A series of Instructions
getc() that are to be executed
more than once
putc()

85
USER DEFINED FUNCTION :
SYNTAX :
retu_datatype func_name(arguments)
{
Body of the function
statements;
return;
}

call the function from main() :


syntax :
func_name(arguments );
86
#include<iostream.h>
Void hai() // function prototype declaration
void hai() //definition
{
Cout<<" Welcome to functions\n";
Cout<<"Good Morning\n";
}
void main()
{
Cout<<"Main, Welcome to functions\n";
hai(); //calling
Cout<<"Bye";
}
87
(Based on Return values and passing Arguments)

 NO ARGUMENT NO RETURN VALUES

 ARGUMENT BUT NO RETURN VALUES


 NO ARGUMENT WITH RETURN VALUES
 WITH ARGUMENT WITH RETURN VALUES

88
NO ARGUMENT NO RETURN VALUES

#include<iostream.h>
#include<conio.h>
void main()
{
void message();
clrscr();
cout<<endl;"Welcome to C++";
message();
cout<<endl<<"end";
getch();
}
void message()
{
cout<<endl<<"Welcome to the Function";
89
}
/* To perform Addition of two numbers
Without Argument and With Return values */
#include<iostream.h>
#include<conio.h>
int add(); //function prototype declaration
void main()
{
int c;
c=add(); /* Return Variable - c */
Cout<<"The sum of two numbers is “<<c;
}
int add()
{
int a,b,c;
Cout<<"Enter two Numbers=";
Cin>>a>>b;
c=a+b;
return(c); 90
WITH ARGUMENT NO RETURN VALUES
#include<iostream.h>
void main()
{
int b,h;
void area(int,int);
cout<<endl<<"Enter Base and Height Values";
cin>>b>>h;
area(b,h);
cout<<endl<<"end";
}
void area(int x,int y)
{
float at;
at=0.5*x*y;
cout<<"area is :"<<at; 91
}
WITH ARGUMENT WITH RETURN VALUES
#include<iostream.h> float area(int x,int y)
#include<conio.h> {
void main() float at;
{ at=0.5*x*y;
int b,h; return at;
float a; }
float area(int,int);
clrscr();
cout<<endl<<"Enter Base and
Height Values";
cin>>b>>h;
a=area(b,h);
cout<<endl<<"Area of the
Triangle is "<<a;
getch();
92
}
Inline function

Basically function are used to save the memory space.


When the compiler sees a function it jumps back to
instruction following to the call.It takes extra time to execute .
To avoid this slow down process inline function are
used.
Inline is a function that is expanded in line when it is
invoked. The compiler replaces the function call when it is
invoked
To make a function as inline ,the inline keyword must
be used before function definition
93
 An Inline function is a function with a few statements that is
expanded inline when it is invoked

 An inline function specifier is actually a request and not a


command to the compiler, hence it may ignore the request and
compile the function as an ordinary function

 Automatic inlining is the process of defining a function inside


the class declaration

94
Common Restrictions while using Inline

 An inline function must be defined

before it is used.

 It should not contain any loops

 It should not be recursive

 It should not contain any

static variables

 It should not contain a goto or a switch statement 95


Example for inline function
#include<iostream.h>
inline float cmtom(int cm)
{
return (float)cm/100;
}
void main()
{
int cm;
clrscr();
cout<<"enter the length in centimeter:"<<endl;
cin>>cm;
cout<<"the equivalent meter value is :"<<cmtom(cm)<<endl;
}

96
 An Inline function is a function with a few statements that is
expanded inline when it is invoked
 An inline function specifier is actually a request and not a
command to the compiler, hence it may ignore the request and
compile the function as an ordinary function

97
FRIEND FUNCTIONS
Why it is used? - The concept behind the encapsulation and
data hiding restrict the non-member function from accessing the
private members of the class.

The best way to access a private data member by a non-


member function is to change a private data member to a public.
but it violates the whole concept of data hiding and
encapsulation.

To solve this problem friend functions are used when we


can access the private or protected members. 98
Friend informs the compiler that the function is
not a member func.Of the class.

Note : friend is not used when the class is defined


outside the class

Syntax :
friend<ret.Type> func_name(arguments);

Member Function Friend Function


It is a part of class definition and is It is no a part of a class
invoked by a particular object
It can access the data depending It can access any data
upon whether the function is private irrespective of the private or
or protected public or protected access
99
#include<iostream.h> void main()
class book {
{ book b;
private : clrscr();
int bno; b.getdata();
char bname[20]; show(b);
public: getch();
void getdata(); }
friend void show(book);
};
void book::getdata()
{
cin>>bno>>bname;
}
void show(book bk)
{
cout<<bk.bno<<bk.bname;
}

100
FRIEND FUNCTIONS
To access the private member of the class inside the
friend function the object of the class should be passed as
an argument to the function

#include<iostream.h>
class second;
class first
{
private :
int no;
public:
first(int n);
friend int add(first,second);
};
class second
{ 101
private : int add(first f,second s)
int n1; {
public: cout<<"First class="<<f.no<<endl;
second(int); cout<<"Second class=“ <<s.n1;
friend int return f.no+s.n1;
add(first,second); }
}; void main()
{
first ::first(int n) first f(10);
{ second s(20);
no=n; clrscr();
} cout<<"\n The Result is "<<add(f,s);
second ::second(int n) }
{
n1=n;
}

102
FRIEND CLASS
The private members of one class can be accessed
from the member functions Of another class by making
them as friends

#include<iostream.h>
#include<conio.h>
class second;
class first
{
private :
int no;
public:
friend class second;
first(int n)
{
103
no=n;
}};
class second
{
public:
void show(first f)
{
cout<<f.no;
}
};
void main()
{
first f(10);
second s;
s.show(f);
getch();
} 104
 The friend function acts as a bridge between two objects of

different classes which can access even the private members of

the class

 A friend class is a class whose members functions are all

friend functions of another class

105
Math Library Functions

106
Overloading

• Another powerful and useful concept of object


oriented programming is overloading
• which allows operation with the same name but
different semantics and different ways of
implementation to be invoked for object of differnt
types.
• For instance,binary operation can be overloaded for
complex number arrays,set or list 107
Function Overloading
• C++ enable two or more functions with
the same name but with different types of
arguments or different sequence of arguments or
different number of arguments. It is also called as
“Function Polymorphism”

• Two or more functions with the same name but with


different types of arguments
108
cin>>breadth;
// Write a C++ program to find
area=length*breadth;
the area of the triangle using
}
Memeber Function Overloading
void showdata(){
#include<iostream.h>
cout<<"Length is:"<<length;
class rectangle
cout<<"Breadth is :"<<breadth;
{
cout<<"The Area is :"<<area;
private :
}
int length,breadth,area;
};
public :
void main()
void getdata() {
cout<<"Enter Length Value :";
{
cin>>length; rectangle r1,r2;
cout<<"Enter breadth Value :”; cout<<"Enter the detail "<<endl;
cin>>breadth; r1.getdata();
area=length*breadth; } r1.showdata();
void getdata(int a) cout<<"Enter the detail"<<endl;
{ r2.getdata(5);
length=a; r2.showdata(); 109
cout<<"Enter breadth Value :"<<endl; }
Difference between Overloading
and Overriding
Allows a function to be given more
than one definition
Overloading
The types of arguments or number
of arguments which the function
takes determines which definition
will be used

Overriding
It is the ability to change the
definition of the base class method
by writing a code for them in the
sub-class of an inheritance 110
Function Overloading is the ability to write more than on
function with the same name with different number ,type and
sequence of arguments. It is also referred as “Function
polymorphism”

111
+
Simply defined as a structure that combines
the objects with some attributes (data
structure) and some behavior (operation)
112
Structure
It is a user-defined data type.

It provides a method for packing together


data of different type.

struct student
{
char name[20];
int rollno;
float marks;
} 113
Limitations of structure:

1. Do not permit data hiding.


2. Struct types cannot be treated
as built in types.
3. It does not contain member
functions.

114
• Extensions to structures:

CLASS

• It is a user-defined data type.

• It provides a method for packing together


data of different type.

• Class contains data, an code to


manipulate that data.

• It behaves like built in types.


115
General form:
class classname
{ private :
variable declarations;
function declarations;
public :
variable declarations;
function declarations;
};

class name – name of the class

private and public : - Default access specifier is Private.


The members that have been declared as private can be
accessed only from within the class.
Whereas, public members can be accessed from outside the
116
class
Data hiding is possible in c++ through private keyword.

Data member:
The variable declared within the class .

Member function:
The function declared within the class.

Ex:

class sample
{
private :
int a;
float b; // a and b are data members
public :
void get(); // get() and put() are member functions
void put(); }; 117
Creating Object :
Once a class is defined,we have to create variable of that type by
using the class name.
Classname obj1,obj2…objn;
obj1, ob2, objn – any valid c++ variable.
Ex.
sample a1,a2; where a1,a2 are objects of a class sample.

Accessing class member :


For accessing the members of a class , dot (.) operator is used.
Objname. Function_name(argument-list);
Ex.
a1.get()
a1.show();
But the private members of a class can never be accessed outside of the
class .
It can be accessed only by the public members of a own class.
118
objectname.func_name(arguments);

119
Defining Member Functions:

•Inside the class definition.


•Outside the Class Definition:

120
Inside the Class Definition:
When a function is defined inside a class , it is treated as an inline
function. So the restrictions & limitations that apply to inline functions are also
applicable. Normally, only small functions are defined inside the class definition.
class sample
{
void sample::get()
{
cout<<”Enter values for a and b”<<endl;
cin>>a>>b;
}
void sample::show()
{
cout<<a<<b;
}};
int main()
{
sample s;
s.show();
121
return 0;
Write a Program to calculate the area of a circle
using class & Object
#include<iostream.h>
#include<conio.h>
class raji
{
private:
int radius;
float area;
public:
void getdata()
{
cout<<"Enter the radius"<<endl;
cin>>radius; 122

}
void calculate()
{
area=3.14*radius*radius;
}
void showdata()
{
cout<<"The area of the circle is "<<area<<endl;
}
};
void main()
{
raji r;
r.getdata();
r.calculate();
r.showdata();
getch();
}

Enter the Radius : 2


The area of the circle is
123
#include<iostream.h> void main()
#include<conio.h> {
class smallobj smallobj a1,a2;
{ clrscr();
private : a1.setdata(2500);
int s;
a2.setdata(4000);
public :
void setdata(int d)
a1.showdata();
{ a2.showdata();
s=d; getch();
} }
void showdata()
{
cout<<endl<<"the Data is
"<<s;
}
}; 124
Class & Objects Example void showdist()
#include<iostream.h> {
#include<conio.h> cout<<endl<<feet<<endl<<inches;
class distance }
{ };
private:
int feet; void main()
float inches; {
public : distance dist1,dist2;
void setdist(int ft,float in) clrscr();
{ dist1.setdist(11,6.25);
feet=ft; dist2.getdist();
inches=in; dist1.showdist();
} dist2.showdist();
getch();
void getdist() }
{
cout<<endl<<"Enter Feet and Inches
Value:";
cin>>feet>>inches;
} 125
For defining the function outside the class, the scope
resolution operator is used.

The general form of a member function definition is


return-type class-name :: function-name (argument
declaration)

{ function body;

}
Example:
class sample
{ private :
int a;
float b;
public :
void get();
void show (); }; 126
void sample::get()
{
cout<<”Enter values for a and b”<<endl;
cin>>a>>b;
}
void sample::show()
{
cout<<a<<b;
}
int main()
{
sample s;
s.get();
s.show();
return 0;
}

127
Scope Resolution Operator (::) void circle::calculate()
The member function of {
A program are defined outside area=3.14*radius*radius;
}
the boundary of the class using
void circle::show()
the scope resolution operator(::)
{
#include<iostream.h>
class circle { cout<<"Area"<<area;
private: }
int radius; void main() {
float area; circle r;
public: r.getdata();
void getdata(); r.calculate();
void get(int r); r.show();
void calculate(); r.get(100);
void show(); r.calculate();
}; r.show();
void circle::getdata(){ }
cout<<"RADIUS"<<endl; RESULT :
cin>>radius; }
ENTER THE RADIUS : 5
void circle::get(int r) {
128
radius=r; } Area FOR 5=78.5
Area FOR 100=31400
Private Member Functions

129
#include<iostream.h> void main()
#include<conio.h> {
const int MAX=100; stack s1;
class stack s1.push(11);
{ s1.push(22);
private: cout<<" Ist Data :"<<s1.pop();
int st[MAX]; cout<<" IInd Data :"<<s1.pop();
int top; s1.push(33);
public : s1.push(44);
stack() { s1.push(55);
top=0; } s1.push(66);
void push(int v) { cout<<" III Data :"<<s1.pop()<<endl;
st [++top]=v; } cout<<" IV Data :"<<s1.pop()<<endl;
int pop() cout<<" V Data :"<<s1.pop()<<endl;
{ cout<<" VI Data :"<<s1.pop()<<endl;
return st[top--]; getch();
} } 130
};
ARRAY OF OBJECTS I void main()
#include<iostream.h> {
const int MAX=100; Distance dist[MAX];
class Distance int n=0;
{ char ans;
private: cout<<endl;
int feet; do
float inches; {
public : cout<<"\n Enter Distance "<<n+1;
void get() dist[n++].get();
{ cout<<"\n Another Data [y/n]?";
cout<<"\n Enter Feet Value :"; cin>>ans;
cin>>feet; }while(ans != 'n');
cout<<"\n Enter Inche Value :";
cin>>inches; for(int j=0;j<n;j++)
} {
void show() cout<<"Distance Number "<<j+1<<"
{ Is ";
cout<<feet<<"\ dist[j].show();
t"<<inches<<endl; }
} } 131

};
ARRAY OF OBJECTS II
#include<iostream.h> void calculate() {
area=3.14*radius*radius;
#include<conio.h> }
class circle { void show() {
cout<<"the area is "<<area<<endl;
private: }
int area, radius; };
void main() {
public: int i;
void getdata() { circle e[5];
for(i=0;i<5;i++)
cout<<"Enter the radius {
value"<<endl; e[i].getdata();
cin>>radius; e[i].calculate();
e[i].show(); }
} getch(); } 132
Output
Enter the radius value 1
The area is 3
Enter the radius value 2
The area is 12
Enter the radius value 3
The area is 28
Enter the radius value 4
The area is 50
Enter the radius value 4
The area is 50 133
Memory Allocation for Objects

134
STATIC DATA MEMBER
A data member of a class can be qualified as static.
Properties of static member variable are

• It is initialized to zero when the first object is created.

• Only one copy of that member is created for the entire


class and is shared by all the objects of that class.

• It is visible only within the class, but its life time is the
entire program.

• The type and scope of each static member variable must be


defined outside of the class.
data_type cname::var 135
STATIC MEMBER FUNCTION
Member function of a class can also be declared as static.
But the static member function can access only static data
member.

Syntax
static ret_type fun_name(argu)
{
//statements
}

136
// Program for Static Data Member //Program for Static Data Member Function
#include<iostream.h> #include<iostream.h>
#include<conio.h> #include<conio.h>
class item
class foo {
{ int n;
private: static int c;
static int count; public:
public: void get()
foo() {
{ n = 10;
c++;
count++; }
} static void put()
int getcount() {
{ cout<<c;
return count; //cout<<n;
} }
}; };
int item::c;
int foo::count=10; void main()
void main() {
{ item a,b,c;
foo f1,f2,f3; clrscr();
clrscr(); a.get();
cout<<"\n Count is "<<f1.getcount(); b.get();
cout<<"\n Count is "<<f2.getcount(); c.get();
a.put();
cout<<"\n Count is "<<f3.getcount();
getch();
getch(); } 137
}
Array of Objects

138
139
140
Each class specification starts with the keyword “class”

The Class Specification must always end with a semicolon (;)

Data abstraction is the ability to create user-defined data


types for modeling real world objects using built-in data types.

Classes are used for data abstraction by hiding the


implementation of a type in the “private” part.

141
Constructor is a non-static special member
function which that is automatically called when an
object is created
It can be used to initalize the class members

Syntax
Classname(<argument>)
{
Statements;
}
Note : Argument is optional
142
RULES
Classname and function name must be same
 It should be declared inside public
 It has no return types
 It may have arguments (optional)
If it does not has any arguments, it is called default
constructor
If it has arguments, it is called overloaded constructor
So a program can have any number of constructor
It cannot be Virtual
It cannot refer to their address
Cannot inherited through derived class call the base class143
constructor
Basic Rules on Constructors
• A constructor is a method that has the same name
as its class.
• Constructors do not return values. They have no
return type specified.
• Constructors can have arguments.
• Constructors can be overloaded.
General Format
To define Constructor by using class-name
class_name ( )
{
Initialization of data members;
144
}
class student
{
int rno, mark1, mark2, mark3;
public:
student ( )
{
rno = 0;
mark1 = 0;
mark2 = 0;
mark3 = 0;
}
void display ( )
{
cout << “ Rno=”<< rno << endl;
cout << “ Mark1=”<< mark1<< endl;
cout << “ Mark2=”<< mark2<< endl;
cout << “ Mark3=”<< mark3<< endl;
}} 145
void main ( )
{
student s;  Constructor Called when object ‘s’ is created

s.display ( );
getch( );
}

The output is
Rno=0
Mark1=0
Mark2=0
Mark3=0

146
Types of Constructors
1. Default Constructor
2. Parameterized Constructor
3. Copy Constructor

Default Constructor
The default constructor is a constructor with no arguments,or a
constructor that provides defaults for all arguments. If the class does
not contain any Constructor, then the compiler will generate a
default constructor.

The compiler generated default constructor


class_name ( )
{}
147
Parameterized Constructor
Constructors can also take parameters
General form
class_name (datatype arg1, datatype arg2, … )
{
Initialization of data members;
}

class student
{
int rno, mark1, mark2, mark3;
public:
student (int r, int m1, int m2, int m3 )
{
rno = r;
mark1 = m1;
mark2 = m2;
mark3 = m3; 148
}
void display ( )
{
cout << “ Rno=”<< rno << endl;
cout << “ Mark1=”<< mark1<< endl;
cout << “ Mark2=”<< mark2<< endl;
cout << “ Mark3=”<< mark3<< endl;

}
}
void main ( )
{
student s(1,56,67,78);  Constructor Called when object ‘s’ is created
s.display ( );
getch( );
}

The output is

Rno=1
Mark1=56
Mark2=67
149
Mark3=78
Constructor Overloading
Since Constructor also a special function, Constructor can be
overloaded like function overloading.
class student
{
int rno, mark1, mark2, mark3;
public:
student ( )  default constructor
{
rno = 0;
mark1 = 0;
mark2 = 0;
mark3 = 0;
}
student (int r, int m1, int m2, int m3 )  parameterized constructor
{
rno = r;
mark1 = m1;
mark2 = m2;
mark3 = m3; 150
}
void display ( )
{
cout << “ Rno=”<< rno << endl;
cout << “ Mark1=”<< mark1<< endl;
cout << “ Mark2=”<< mark2<< endl;
cout << “ Mark3=”<< mark3<< endl;

}
}
void main ( )
{
student s1;  The default Constructor Called when object ‘s1’ is created

student s2(1,56,67,78);  The parameterized Constructor Called when object


‘s2’ is created
cout << “Object s1 values” << endl;
s1.display ( );
cout << “Object s2 values” << endl;
s2.display ( );
getch( );
}
151
The output is
Object s1 values
Rno=0
Mark1=0
Mark2=0
Mark3=0

Object s2 values
Rno=1
Mark1=56
Mark2=67
Mark3=78
152
Copy Constructor
To initialize one object by another.
General form
class_name (class_name &o) o  reference to the object
{
body of constructor
}

class student
{
int rno, mark1, mark2, mark3;
public:
student ( )  default constructor
{
rno = 0;
mark1 = 0;
mark2 = 0;
mark3 = 0;
153
}
student (int r, int m1, int m2, int m3 )  parameterized constructor
{
rno = r;
mark1 = m1;
mark2 = m2;
mark3 = m3;
}
student (student &st )  copy constructor
{
rno = st.rno;
mark1 = st.mark1;
mark2 = st.mark2;
mark3 = st.mark3;
}
void display ( )
{
cout << “ Rno=”<< rno << endl;
cout << “ Mark1=”<< mark1<< endl;
cout << “ Mark2=”<< mark2<< endl;
cout << “ Mark3=”<< mark3<< endl; 154
} }
void main ( )
{
student s1;  The default Constructor Called when object ‘s1’ is
created

student s2(1,56,67,78);  The parameterized Constructor Called when


object ‘s2’ is created
student s3(s2 )  The copy Constructor Called when object ‘s3’ is
created
cout << “Object s1 values” << endl;
s1.display ( );
cout << “Object s2 values” << endl;
s2.display ( );
cout << “Object s3 values” << endl;
s3.display ( );
getch( );
} 155
The output is
Object s1 values
Rno=0
Mark1=0
Mark2=0
Mark3=0

Object s2 values
Rno=1
Mark1=56
Mark2=67
Mark3=78

Object s3 values
Rno=1
Mark1=56
Mark2=67 156
Mark3=78
//Constructor Overloading circle(int x,int y)
#include<iostream.h> {
#include<conio.h> b=x;
class circle { h=y;
private: area=0.5*b*h;
int radius; cout<< "\n area of the Triangle is " <<
float area; area;
int b,h; }
public: };
circle() void main()
{ {
cout<<"Enter the radius "<<endl; clrscr();
cin>>radius; circle c;
area=3.14 * radius * radius; circle d1(6);
cout<<"area of the circle"<< area; circle c1(3,4);
} getch();
circle(int r) }
{
radius=r;
area=3.14 * radius * radius;
cout<< "\n area of the circle is " << 157
area;
Destructor is a special member function
that is called automatically when an object is destroyed
that have been created by constructor
It can be used to deallocate the memory space

Need for destructor


The programmer is relived of the task of clearing
the memory space occupied by the data members every
time an object goes out of scope.
158
RULES
 It should be declared inside public
 It has no return types
 It has no argument or parameters
 Prefixed by tilde(~) symbol
 So a program can have only one destructor

Syntax
~Classname( )
{
Statements;
}
159
Has to be
destroyed complier
object
calls

Destructor
De-allocates

memory

160
Destructor
To deallocate the memory of object when the object goes
out of the scope
When an object is destroyed, the destructor is automatically
called. If the class does not contain destructor function, the

compiler will generate the default destructor function.


Reason for the destructor needed
• An object may need to deallocate the memory that it had
previously allocated
• An object may need to close a file that it had opened.
Basic rules on Destructor
• A destructor is a special method that has the same name as
its class prefixed by a tilde ~.
• Destructors do not return any values. They have no return
type specified.
• Destructors have no arguments and thus cannot 161
be
overloaded
General format
~class_name ()
{
body of destructor;
}
class sample
{
int n,m;
public:
sample( )  Constructor
{
n = m = 0;
}
~sample ( )  Destructor
{
cout << “Destructor Called” << endl;
}
void display ( )
{
cout << “ N = ”<< n << endl << “ M=”<< m<< endl; 162
} }
void main ( )
{
student s;  Constructor Called when object ‘s’ is created

s.display ( );
getch( );
}

The output is
N=0
M=0
Destructor Called

163
A constructor is a special member function which is executed

automatically when an object is created

A Destructor is a special member function which is executed

automatically when an object is destroyed

164
Operator Overloading refers to giving the normal C++
Operators, such as +,*,<= etc., additional meanings when
they are applied to user defined data types.
simply defined as to create new definitions for
operators.
2. Data type conversions is closely connected with operator
overloading.
Syntax :
<ret.datatype> operator <operator name>()
{
---
--- 165
}
The steps involved an operator are :

1. Create a class that defines a data type that is to be used


in the overloading operation

2. Declare the operator function as either a member


function or a friend function inside the class

3. Define the operator function either inside or outside the


class

4. Use the operator in the main() function 166


All the operators can be overloaded using friend
function except () [] -> and =. These operators must
be defined by using a member function.

ASSIGNMENT OPERATOR OVERLOADING RULES :


The operator function for the assignment operator
are inherited by any derived class. Friend functions
cannot be used to overload the assignment operator

167
The operators that can be overloaded
are
+ - * / % ^ &
| _ != < > <= >= +=
-+ *= != ++ -- [ ] ()
|| &= && -> , new delete

The operators that cannot be overloaded are


#
.(member operator)
::
sizeof
?:
168
The basic meaning of an operator cannot be changed

New operators cannot be overloaded. The existing operators


can be overloaded

The procedence and associativity of an operator cannot be


altered
The syntax of overloaded operator is same as ordinary operators

The number of operands that an operator takes cannot be


changed

169
OVERLOADING UNARY void main()
OPERATOR ++ {
#include<iostream.h> counter c1,c2;
class counter cout<<"\n c1 ="<<c1.get_count();
{ cout<<"\n c2 ="<<c2.get_count();
private :
unsigned int count; ++c1;
public :
counter() c2=++c1;
{
count=0; cout<<"\n c1 ="<<c1.get_count();
} cout<<"\n c2 ="<<c2.get_count();
int get_count() { }
return count; }
counter operator ++() OUTPUT :
{
C1 = 0
++count;
counter temp; C2 = 0
temp.count=count;
return temp; C1 = 2
}}; C1 = 2 170
Overloading Binary Operator + void get()
#include<iostream.h> {
class Distance cout<<"\n Enter Feet :";
{ cin>>feet;
private :
int feet; cout<<"\n Enter inches :";
float inches; cin>>inches;
public : }
Distance() void show()
{ {
feet=0; cout<<feet<<inches<<"\n";
inches=0.0; }
} Distance operator +(Distance);
};
Distance(int ft,float in)
{
feet=ft;
inches=in;
}

171
Distance Distance ::operator +(Distance d2)
{
int f=feet+d2.feet;
float i=inches+d2.inches;
return Distance(f,i);
}
void main()
{ OUTPUT :
Distance d1,d3,d4; Enter feet : 5
Distance d2(11,6.25); Enter inches : 4.4
d1.get(); d1 = 5 4.4
d3=d1+d2; d2 = 11 6.25
d3 = 16 10.65
d4=d1+d2+d3;
d4 = 32 21.299999
cout<<"\n D1= ";d1.show();
cout<<"\n D2= ";d2.show();
cout<<"\n D3= ";d3.show();
cout<<"\n D4= ";d4.show();
}

172
OVERLOADING MINUS OPERATOR (-)
#include<iostream.h>
class minus
{
private :
int a,b;
public:
void get(int i,int j);
void display(void);
friend void operator -(minus &m);
};
void minus ::get(int i,int j)
{
a=i;
b=j;
}
void minus::display(void)
{
cout<<a<<"\t"<<b<<endl;
} 173
void operator -(minus &m)
{
m.a=-m.a;
m.b=-m.b; OUTPUT :
-100 -50
}
void main()
{
minus m;
m.get(100,50);
m.display();
-m;
m.display();
}
174
OVERLOADING THE SUBSRIPTOPERATOR []
#include<iostream.h> for(i=1;i<=SIZE;i++)
const int SIZE=5; {
class array // control is transferred to the operator
{ function call int operator [] (int i)

private :
int a[SIZE]; cout<<a1[i]<<"\t";}
public: }
int operator [] (int i)
{
return i; OUTPUT :
} 1
}; 2
3
void main() 4
{ 5
array a1;
int i; 175
Overloading arithmetic operator
#include<iostream.h>
class operations void accept()
{ {
public : cout<<"\n Enter 2 Values";
int a,b,c,d,e; cin>>a>>b;
operations operator + (operations p)
OUTPUT :
}
{ Enter 2
}; values : 20
p.c=p.a+p.b; void main()
return p;} 20
{
operations operator - (operations q)
operations x; Addition
{
q.d=q.a-q.b; x.accept(); -> 40
return q; x.c=x.a+x.b; Subtractio
} cout<<x.c<<endl; n -> 0
operations operator * (operations r) x.d=x.a-x.b; Multiplicati
{ cout<<x.d<<endl; on -> 400
r.e=r.a*r.b; x.e=x.a*x.b;
return r; cout<<x.e<<endl; 176
} }
177
178
 We can give different meaning to an operator , depending upon
the types of arguments called “operator Overloading” that cannot
be overloaded as Operator polymorphism

The keyword “Operator” is used to form the name of a function


that overloads an operator

An operator can be overloaded by a member function of a class


or by a friend function

Overloading an increment & Decrement operator has two


forms, the Prefix and Postfix form.
179
 The Number of arguments ,the member function of an unary
operator takes is one.

 The Number of arguments ,the member function of an Binary


Operator takes is two

 The Number of arguments ,the friend function of an unary


operator takes is Nil

 The Number of arguments ,the friend function of a binary


operator takes is one

 The operators that cannot be overloaded are . * :: sizeof() ?:

180
It is the Process of creating a New
class from an existing class.

The Existing class is called Base or


Parent class.

The New class is called as Child or


Derived Class
181
Advantages
It permits code reusability. So, save time and
increase the program reliability.

A programmer can use a class created by another


person or company without modifying it derive other
classes from it that are suited to particular situations

Improve Program Reliability

It Permits code sharing


182
Advantages
The base class need not be changed but can be
adapted to suit the requirements in different
applications.

Saves developers time and effort so that they need


not to spend time to know the core technical facts

183
Class <derived classname> : public
<Base classname>
{
---
----
};

184
Inheritance is the property that allows the
reuse of an existing class to build a new class

Base Class Derived class


Methods Base class methods
and +
Properties Additional methods

185
Inheritance

Single Inheritance Hierarchical


Inheritance

Multilevel Multiple Inheritance


Inheritance

186
187
Single Inheritance
A class can be derived from a
single base class is called single inheritance

Multiple Inheritance
Base Class
Class A Class B

sub Class
Class C
188
Multilevel Inheritance

Class A

Class B
Hierarchical Inheritance

Class C Base Class

sub Class 3 sub Class 1 sub Class 2


189
Hybrid Inheritance

Hybrid is nothing but the combination of


Multilevel and multiple Inheritance
Lecturer

Multi level
Inheritance
Marks Department

Student
Multiple
Inheritance

190
Base Class Derived class Visibility
Visibility
Public derivation Private Derivation

Private Not inherited Not Inherited

Public protected private

Protected public private

191
//Example for Single inheritance void hdca::hdca_getfees()
#include<iostream.h> {
class pcp cout<<"Enter the fees amount :";
{ cin>>unix>>c>>cpp;
private: }
float dos,msoffice,foxpro;
public:
void hdca::hdca_listfees()
void pcp_getfees();
{
void pcp_listfees();
};
cout<<"Unix: "<<unix<<endl;
class hdca:public pcp cout<<"C: "<<c<<endl;
{ cout<<"C++: "<<cpp<<endl;
private: }
float unix,c,cpp; void main()
public: {
void hdca_getfees(); clrscr();
void hdca_listfees(); hdca h;
}; cout<<endl<<"Fees detail for PCP"<<endl;
void pcp::pcp_getfees() h.pcp_getfees();
{ cout<<endl<<"Fees detail for HDCA"<<endl;
cout<<"Enter the fees amount for "; h.hdca_getfees();
cin>>dos>>msoffice>>foxpro;
cout<<endl<<"Fees list for PCP"<<endl;
}
h.pcp_listfees();
void pcp::pcp_listfees()
cout<<endl<<"Fees list for HDCA"<<endl;
{ h.hdca_listfees();
cout<<"Dos: "<<dos<<endl; getch();
cout<<"Msoffice: "<<msoffice<<endl; }
cout<<"Foxpro: "<<foxpro<<endl; 192
}
It is the process of creating new class from more than one base
classes.
Syntax :
class <derived class >:<access specifier>
base_class1,<access specifier> base_class2...
{
private :
// members;
protected :
// members;
public :
//memebers;
};

193
#include<iostream.h> class deri:public base1,public
class base1 base2
{ {
protected : private:
int var1; int var3;
public : public :
void disp_base1() { deri(int a,int b,int c)
cout<<"var1 "<<var1<<endl; {
}}; var1=a;
class base2 var2=b;
{ var3=c;
protected : }
int var2; void disp_me()
public : {
void disp_base2() cout<<"var3 is"<<var3;
{ } };
cout<<"var2 is"<<var2<<endl; Void main()
}}; {
194
void main()
{
deri d(10,20,30);
clrscr();
d.disp_base1();
d.disp_base2();
d.disp_me();
getch();
}

195
AMBIGUITY IN MULTIPLE
class deri:public base1,public base2
INHERITANCE
#include<iostream.h>
{
};
class base1
{ void main()
public:
int i; {
void disp() deri d;
{
d.i=10;
cout<<"base1 value"<<i<<"\n";
} d.disp();
}; clrscr();
class base2
{ /*deri d;
public: d.base1::i=10;
int i;
d.base2::i=20;
void disp()
{ d.base1::disp();
cout<<"base2 value"<<i; d.base2::disp();
}
}; getch();*/
}

RESULT : AMBIGUITY ERROR OCCURRED


196
//Example for MultiLevel inheritance class deri:public base1,public base2
#include<iostream.h> {
#include<conio.h> };
class publications
{ void main()
private : {
int book_no; /*deri d;
public : d.i=10;
void getdata() d.disp();*/
{ clrscr();
cout<<"\n"<<"Enter Book Number:"; deri d;
cin>>book_no; d.base1::i=10;
} d.base2::i=20;
void putdata() d.base1::disp();
{ d.base2::disp();
cout<<book_no<<endl; getch();
} }
};
class author: public publications
{
private :
char author_name[20];
public :
void getdata()
{
publications::getdata();
cout<<"Enter author name";
cin>>author_name;
} 197
Inheritance

Class Employee
Common to
Name Director

Age Manager
Employee id
Salary Secretary

Department Clerk

198
Inheritance

Employee

Director Manager Secretary Clerk

Each of the sub-classes is considered to be derived from the


parent class Employee
199
Example for Hierarchical void getdata()
{
inheritance employee::getdata();
#include<iostream.h> cout<<"Enter Basic Salary \n";
class employee cin>>basic;
{ }
private : }
int empno; void putdata()
char empname[20]; {
public : da=0.30*basic;
void getdata(){ hra=0.15*basic;
cout<<"\n Enter Employee No"; cca=0.05*basic;
cin>>empno; pf=0.12*basic;
cout<<"\n Enter Employee name "; special_allowances=0.4*basic;
cin>>empname;} salary=basic+da+hra+cca+special_allowance
void putdata(){ s-pf;
cout<<"\n Employee No"<<empno; employee::putdata();
cout<<"\n Employee name "<<empname;} cout<<endl<<salary;
}; }};
class manager :public employee class supervisor : public employee
{ {
private : private :
float basic; float basic;
public : public :
float salary; float salary;
float da; float da;
float hra; float hra;
float cca; float cca;
float pf; float pf; 200
float special_allowances; float special_allowances;
void getdata() void putdata()
{ {
employee::getdata(); salary=wages+incentive;
cout<<"Enter Basic Salary \n";
cin>>basic;
employee::putdata();
} cout<<endl<<salary;
void putdata() }
{ };
da=0.30*basic; void main()
hra=0.15*basic; {
cca=0.05*basic; manager m;
pf=0.12*basic;
special_allowances=0.4*basic;
supervisor s;
salary=basic+da+hra+cca+special_allowa worker w;
nces-pf; clrscr();
employee::putdata(); m.getdata();
cout<<endl<<salary; s.getdata();
} w.getdata();
}; w.putdata();
class worker :public employee
{
s.putdata();
public : m.putdata();
float salary; getch();
float wages; }
float incentive;
void getdata()
{
employee::getdata();
cout<<"\n Enter wages & incentives"; 201
cin>>wages>>incentive;
}
HYBRID INHERITANCE void putdata()
{
cout<<"Department name is "<<department_name;
#include<iostream.h>
}
class lecturer
};
{
class marks
private :
{
char lecturer_name[20];
public :
public :
int mark1;
void getdata()
int mark2;
{
int mark3;
cout<<"Enter Lecturer name";
cin>>lecturer_name;
void getdata()
}
{
void putdata()
cout<<"Enter the marks for 3 subjects";
{
cin>>mark1>>mark2>>mark3;
cout<<"lecturer name is
}
"<<lecturer_name;
void putdata()
}
{
};
cout<<"The marks for 3 subjects are "<<mark1<<"\
class department : public lecturer
t"<<mark2<<"\t"<<mark3;
{
}
private :
};
char department_name[20];
public:
class student:public department,public marks
void getdata()
{
{
private:
cout<<"Enter Department name";
int roll_no;
cin>>department_name;
} 202
char student_name[20];
public:
void getdata()
{
department::getdata();
cout<<"Enter the student name";
cin>>student_name;
cout<<"Enter the student Enrollment no";
cin>>roll_no;
marks::getdata();
}
void putdata()
{
department::putdata();
cout<<"The name & rollno is
"<<student_name<<"\t"<<roll_no;
marks::putdata();
}
};

void main()
{
student s;
clrscr();
s.getdata();
s.putdata();
getch();
}
203
#include<iostream.h> void main()
class baseA {
{ baseA b;
public: deriA d;
void show() clrscr();
{ b.show();
cout<<"base class show function“; d.show();
} getch();
}; }
class deriA:public baseA
{
public:
void show()
{
cout<<"derive class show function“;
}};
204
 The class from which members are derived are called as base
class or parent class and the class which derives data from
another class is called as the derived class or child class

 A derived class is always as big as the base class, since the


object of the derived class inherits all the characteristics of the
base class and can add properties of its own.

 Depending upon the access specifiers inheritance is classified


as private, protected and public inheritance

205
 The private members inherited from the base class are
inaccessible to the member functions of the derived class in all
types of inheitance

 A derived class with only one base class is called as Single


Inheritance

 A derived class with one or more than one base class is called
as multiple inheritance

 A base class with more than one derived class is referred to as


the Hierarchical inheritance

 The combination of multilevel and multiple inheritance is


called as Hybrid Inheritance
206
• It is one of pillars of object oriented programming.In an
object oriented language

• polymorphism allows a programmer to purse a course of


action by sending a message to an object without
concerning about how the software system is to implement
the action (i.e One function works as different in different
place)

207
Without Using Virtual Keyword
cin>>name;
#include<iostream.h>
cout<<"Enter the roll no"<<endl;
class base
cin>>rollno;
{
}
public:
void getdata();
void derivedB::display()
void display();
{
};
cout<<"The name is"<<name<<endl;
cout<<"The roll no is"<<rollno<<endl;
class derivedB: public base
}
{
private:
void main()
long int rollno;
{
char name[20];
clrscr();
public:
base *ptr;
void getdata();
derivedB obj;
void display();
ptr=&obj;
};
ptr->getdata();
ptr->display();
void base::getdata()
getch();
{
}
cout<<"base class getdata function";
}
void base::display()
{
cout<<"base class display function";

void derivedB::getdata() 208


{
 Virtual means existing in effect but not in reality.

 It provide a way for a program to decide, when it is


running, what function to call.

 It allows greater flexibility in performing the same


kinds of action on different kinds of objects.

 It actually holds pointers to a variety of derived types

 It is defined and declared in the base class and is then


used by several derived functions by getting up pointers.

209
IMPORTANT CONCEPTS OF VIRTUAL
FUNCTIONS

1.EARLY OR STATIC BINDING - at compile


time rather than run time.

2.LATE OR DYNAMIC BINDING - it is the


process of determining the addresses of functions
at runtime rather than at compile time.

Tree01.ico
210
With Using “virtual” Keyword void derivedB::display()
#include<iostream.h> {
#include<conio.h> cout<<"The name is"<<name<<endl;
class base cout<<"The roll no
{ is"<<rollno<<endl;
public: }
virtual void getdata()=0;
virtual void display()=0; void main()
}; {
clrscr();
class derivedB: public base base *ptr;
{ derivedB obj;
private: ptr=&obj;
long int rollno; ptr->getdata();
char name[20]; ptr->display();
public: getch();
void getdata(); }
void display();
};

void derivedB::getdata()
{
cout<<"Enter the name"<<endl;
cin>>name;
cout<<"Enter the roll no"<<endl;
cin>>rollno; 211
}
 This function should be declared in the base class specifications

 It can be overloaded

 It should be a member function of a class

 There can be virtual destructors

 Constructors cannot be declared as virtual functions

 This function may or may not have function body

 It cannot be an ordinary stand alone function

 These functions are to be accessed by base class pointers

 If there is no code defined for a virtual function in derived class, then base
class function is invoked
212
 A body less virtual function is otherwise called.
Simply defined as virtual functions with no body

 we use the pointer of base class to refer all the


derived objects

 It is a normal practice to have a function in base class


just for implementing virtual function but the actual coding
will be done in derived class only and also the class cannot
be used for creating objects.

213
Polymorphism Using void main()
Array {
#include<iostream.h> base *list[2];
#include<conio.h> base1 b;
class base base2 b1;
{ clrscr();
public:
list[0]=&b;
virtual void show()=0;
}; list[1]=&b1;
class base1:public base list[0]->show();
{ list[1]->show();
public: getch();
void show(){
}
cout<<"\n base1 called";}
};
class base2:public base
{
public:
void show(){
cout<<"\n base2 called"; } 214
};
Abstract classes virtual void getdata()=0;
virtual void putdata()=0;
};
A class that contains atleast void main()
one pure virtual function is said to {
be an abstract class. clrscr();
NOTE : you can use an abstract cout<<"end";
class only act as a base class for getch();
deriving other classes but does not }
create objects

#include<iostream.h>
#include<conio.h>
class book
{
private :
int x;
public :
book()
{
x=0; 215
}
 Polymorphism is defined as the ability of objects of different
classes related by inheritance to respond differently to the same
member function or operator.

 A virtual function is one that does not really exist but never
less appears real to some parts of the program. It provides a
way to decide , when it is running what function to call.

 The function call resolved at compile time is called as static


binding
216
 The function call resolved at runtime is called as dynamic
binding

 The virtual function that has no body is called as pure


virtual function

 The virtual function that is equated to zero is called as a


null virtual function

 If a class contains one or more pure virtual functions, it is


an abstract base class.

217
218
219
220
221
222
223
224
225
226
227
228
229
 A Stream is generally referred to flow of data.

 Different streams are used to represent different kinds of data flow

 Each stream is associated with particular class which contains


member functions and definitions for dealing with that particular kind
of data flow

 The sequence of input bytes are called as Input Stream

 The sequence of output bytes are called as Output Stream

 The cin object with >>operator is used for getting input

 The cout object with <<operator is used for displaying output

 In C++, the number of base and derived classes are available in


Stream I/O classes 230
231
232
The Header File <fstream.h> contains the definitions for file stream
classes
It contain the definitions for three classes. They are
1) ifstream
2) ofstream
3) fstream
Ofstream :
Every object of type ofstream uses a filename to store
information in that file.
Ifstream :
To read the contents from a file we must create an object of
class ifstream.

233
Opening a File
The Open() function is used to open different files that uses the
same stream object.
Syntax : open(“filename”, file mode);

File Mode Description


ios :: in Open file for reading
ios :: out Open file for writing
ios :: app Open file for reading and/or writing the data at
the end of file (append)
ios :: ate Erase the file before reading or
writing(Truncated)
ios :: nocreate Error when opening, if file does not already
exists
ios :: no replace Error when opening, if file does not already
exists, unless ate or app is set
234
ios :: binary Open file in binary mode (not text mode)
Closing a File
To close a file, the member function close() must be used. It takes
no parameters and returns no value.
Syntax : close();

Detecting End-Of-File
It is necessary for preventing any attempt to read data from the
file.
Syntax : eof()

put() and get() functions :


put() function displays a single character on the screen.
Syntax : put(char);
get() function gets a single character from the file
Syntax : get(void)

235
236
237
238
• Modifying an existing System
• Adding a New Item
• Deleting an existing systems

239
Error Handling during File
operations

240
241
File creation(Writing the contents or data to a file )
#include<iostream.h>
#include<conio.h>
#include<fstream.h>
void main() l t:
{ esu l ly
R sf u
ofstream outfile; ces ed
Su reat
char fname[20]; C
cout<<"enter the filename"<<endl;
cin>>fname;
outfile.open(fname);
outfile<<"Sachin"<<endl;
outfile<<"Jackie"<<endl;
outfile<<"Vijay"<<endl;
cout<<"\n "<<"Sucessfully created ";
outfile.close();
} 242
Read the contents(data) from the file
#include<iostream.h> while(!infile.eof())
#include<conio.h> {
#include<stdlib.h> ch=infile.get();
#include<fstream.h> cout<<ch;
void main() }
{ infile.close();
ifstream infile; }
char fname[20];
char ch;
cout<<"enter the filename ";
cin>>fname;
infile.open(fname);
if(infile.fail())
{
cout<<"file does not exist";
exit(1); 243
}
copy the contents from one file into another file
#include<iostream.h> if(outfile.fail())
#include<conio.h> {
#include<stdlib.h> cout<<"unable to create a file";
#include<fstream.h> exit(1);
void main() }
{ while(!infile.eof())
ofstream outfile; {
ifstream infile; ch=infile.get();
char source[10],target[10],ch ; outfile.put(ch);
clrscr(); cout<<ch;
cout<<"enter the source file name"; }
cin>>source; infile.close();
cout<<"enter the target file name"; outfile.close();
cin>>target; getch();
infile.open(source); }
if(infile.fail())
{
cout<<"source file does not exist";
exit(1);
} 244
outfile.open(target);
The getline() and write() functions
These two functions are line oriented input and output functions
respectively.

getline() function reads a complete line until it encounters a


newline character.

Syntax : cin.getline(char*,size);

Char*  holds the inputline

Size  The number of characters to be read

write Function
It is used for displaying a text in a line until it encounters a ‘\n’
characters.

Syntax : cout.write(char*,size); 245


getline() and write() function Example

#include<iostream.h>
#include<conio.h>
void main()
{
char name[50];
clrscr();
Cout<<“Enetr any string”<<endl;
cin.getline(name,40);
cout.write(name,40);
getch();
}

Result
Enter any String : India is My Country

India is My Country
246
 A stream is generally referred to a flow of data.
 Each stream is associated with a particular class which contains
member functions and definitions for dealing with that particular
kind of data flow
 The sequence of input bytes are called Input stream
 The sequence of output bytes are called as output stream
 The Ofstream is used for writing information to a file
 The ifstream class is used for reading information from a file
 The stream class is used for both writing and reading from a file
247
Define Templates

Types of Templates

Explain Function Templates


Explain Class Templates

248
• A generic function defines a general set of operations that will
be applied to various types of data that a function will operate
upon.
• A generic class defines the algorithm that specifies the actual
type of data when objects of that class are created
• A generic class and a generic function is created using the
keyword “Template”

ADVANTAGES :
 It helps to define classes that are general in nature.
 It makes the process simpler and safer
249
// TEMPLATES DEFINITION
#include<iostream.h>
#include<conio.h> Output :
template <class T> 19
T max(T x,T y)
6.7
{
return(x>y)?x:y;
};
void main()
{
clrscr();
cout<<max(17,19)<<endl;
cout<<max(1.5,6.7)<<endl;
cout<<max('A','B')<<endl;
getch(); 250
}
function template Example
=====================

#include<iostream.h>
#include<conio.h>
template<class T1,class T2>
void good(T1 x,T2 y)
{
clrscr();
cout<<x<<" "<<y<<endl;
}
void main()
{
good(456,"hello"); Output :
getch(); 456 hello
}
251
// Function template example.
swapargs(i, j); // swap integers
#include <iostream>
swapargs(x, y); // swap floats
using namespace std;
swapargs(a, b); // swap chars
// This is a function template.
cout << "Swapped i, j: " << i << '
template <class X> void swapargs(X &a,
' << j << '\n';
X &b)
cout << "Swapped x, y: " << x <<
{
' ' << y << '\n';
X temp;
cout << "Swapped a, b: " << a <<
temp = a;
' ' << b << '\n';
a = b;
return 0;
b = temp;
}
}

int main()
{
int i=10, j=20;
double x=10.1, y=23.3;
char a='x', b='z';
cout << "Original i, j: " << i << ' ' << j <<
'\n';
cout << "Original x, y: " << x << ' ' << y
<< '\n';
cout << "Original a, b: " << a << ' ' << b
252
<< '\n';
For Example
#include<iostream.h> :
void function1(int i)
{
cout<<"The value of i is"<<i<<endl;
}
void function2(double d)
{
cout<<"The integer part is"<<int(d);
d - = int(d);
cout<<"The factorial part is"<<d;
}
Output :
void main()
{ The value of i is 2
function1 (2); The integer part is 23
function2 (23.5);
253
} The factorial part is 0.5
A program to define the function void main()
template for swapping two items of {
the various data type as integer and int ix,iy;
floating point number float fx,fy;
cout<<"Enter any twoNo \n";
#include<iostream.h> cin>>ix>>iy;
#include<conio.h> cout<<"Enter any 2 Real No";
template<class T>T swap( T &first, T cin>>fx>>fy;
&second) swap(ix,iy);
{ cout<<"after swapping;
T temp; cout<<ix <<iy;
temp = first; swap(fx,fy);
first = second; cout<<"After swapping : cout<<fx <<
second = temp; fy<<endl;
return(0); getch();
} }

int swap(int &a,int &b); 254


Default Constructor void main()
#include<iostream.h> {
#include<conio.h> clrscr();
template<class T> sample<int> obj1;
class sample obj1.display();
{ sample<int> obj2;
private: obj2.display();
T value; getch();
public: }
sample(T=0)
{ //it prints the ascii value of the int
} and float.
void display()
{ Overloading -> We have to pass a
cout<<"default constructor is value for the variable and have to
called"<<endl; implement
cout<<"Content of the value
"<<value<<endl; Overridding -> To overwrite the
} method or function.
};
255
CLASS TEMPLATE
#include<iostream.h>
template<class q>
class sample
{
private:
q value,value1,value2;
public:
get();
sum();
template <class q>
{
void sample<q>::get()
{
cout<<"Enter a value for the value1"<<endl;
cin>>value1;
cout<<"Enter a value for the value2"<<endl;
256
cin>>value2;
} cout<<"Enter the integer
} value"<<endl;
template<class q> obj1.get();
obj1.sum();
void sample<q>::sum() cout<<"Enter the floating
{ value"<<endl;
q value; obj2.get();
value=value1+value2; obj2.sum();
cout<<"The added value getch();
is"<<value<<endl; }
}

};
void main()
{
clrscr();
sample<int>obj1;
sample<float>obj2; 257
 A generic function defines a general set of operations
that will be applied to various types of data that a function
will operate upon.

A generic class defines the algorithm that specifies the


actual type of data when objects of that class are created

A generic class and a generic function is created using


the keyword “template”
 Rules to be followed for all programs written in C
258

You might also like