Sev C++ All
Sev C++ All
Prepared by.,
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
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
Problem
Identification Analysis
Maintenance Design
Implementation Development
Testing
16
Data acquisition Systems
Client/Server Computing
17
Encapsulation
Data Abstraction
Inheritance
Polymorphism
Class 18
Grouping of data and methods into a
single entity is known as Data
Encapsulation
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
application
Methods
22
It is the process of
creating a new class from
an existing class
23
Reusability can be achieved through inheritance
Animals
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
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.
33
For Example
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
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
#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;
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
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
#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.
Digits – 0,1,2,3,…7,8,9
71
Variables are named locations in memory that are used to
hold a value that may be modified by the program.
K5.ico ANIMATAY006.ICO
Data type Variablename;
Valid Examples :
CSC avg_val m1
Chennai Anu mark_1
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.
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 (//)
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;
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;
}
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
94
Common Restrictions while using Inline
before it is used.
static variables
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.
Syntax :
friend<ret.Type> func_name(arguments);
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
the class
105
Math Library Functions
106
Overloading
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.
struct student
{
char name[20];
int rollno;
float marks;
} 113
Limitations of structure:
114
• Extensions to structures:
CLASS
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.
119
Defining Member Functions:
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();
}
{ 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 visible only within the class, but its life time is the
entire program.
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”
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.
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
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
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
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
s.display ( );
getch( );
}
The output is
N=0
M=0
Destructor Called
163
A constructor is a special member function which is executed
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 :
167
The operators that can be overloaded
are
+ - * / % ^ &
| _ != < > <= >= +=
-+ *= != ++ -- [ ] ()
|| &= && -> , new delete
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
180
It is the Process of creating a New
class from an existing class.
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
185
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
Multi level
Inheritance
Marks Department
Student
Multiple
Inheritance
190
Base Class Derived class Visibility
Visibility
Public derivation Private Derivation
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();*/
}
Class Employee
Common to
Name Director
Age Manager
Employee id
Salary Secretary
Department Clerk
198
Inheritance
Employee
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
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 one or more than one base class is called
as multiple inheritance
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";
209
IMPORTANT CONCEPTS OF VIRTUAL
FUNCTIONS
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
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
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.
217
218
219
220
221
222
223
224
225
226
227
228
229
A Stream is generally referred to flow of data.
233
Opening a File
The Open() function is used to open different files that uses the
same stream object.
Syntax : open(“filename”, file mode);
Detecting End-Of-File
It is necessary for preventing any attempt to read data from the
file.
Syntax : eof()
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.
Syntax : cin.getline(char*,size);
write Function
It is used for displaying a text in a line until it encounters a ‘\n’
characters.
#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
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();
} }
};
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.