Download as pdf or txt
Download as pdf or txt
You are on page 1of 89

Object oriented programming with C++

Introduction of C++
Key concepts of OOPS:
UNIT-I: Objects
Introduction to C++: Key concepts of OOPs Advantages object Classes
Methods
oriented languages Input and output in C++ -Streams in C++ - Pre-
Data Abstraction
Defined Streams Unformatted console I/O operation Formatted Encapsulation
console I/O operations C++ Declarations Control structures: Inheritance
Decision Making statements If....Else Jump GOTO Break Polymorphism
Dynamic Binding
Continue Switch case statements Loops in C++ : For While Do...
Message Passing
While Loops Functions in C++ - In Line Functions Function Reusability
Overloading. Delagation
Genericity

Methods:
Objects:
Operation required for an object entity coded in a class.
Objects are the basic run time entities in an object-oriented system. They may represent a
operation defined in a class.
person, a place, a bank account, a table of data or any item that the program has to handle.
Action are defined in a method.
They may also represent user-defined data such as vectors, time and lists. Class contains private & public methods or number function.
Classes : Member function contains data members.
(e.g)
The entire set of data and code of an object can be made a user-defined data type with the
class student
help of class. In fact, objects are variables of the type class. Once a class has been defined,
{
we can create any number of objects belonging to that class. Each object is associated with
Private:
the data of type class with which they are created. A class is thus a collection of objects Data members;
similar types. Public:
For examples, Mango, Apple and orange members of class fruit. Classes are user-defined Method()
that types and behave like the built-in types of a programming language.
};
void main()
{
student s Polymorphism:
s.method name();
Polymorphism is another important OOP concept. Polymorphism, a Greek term, means the
}
Data Abstraction: ability to take more than on form. An operation may exhibit different behavior is different
Abstraction refers to the act of representing essential features without including the background instances. The behavior depends upon the types of data used in the operation.
details or explanation.
Dynamic Binding:
(e.g) size,cost,height,weight.
Encapsulation : Binding refers to the linking of a procedure call to the code to be executed in response to
The wrapping up of data and function into a single unit (called class) is known as encapsulation. the call. Dynamic binding means that the code associated with a given procedure call is not
Data and encapsulation is the most striking feature of a class. The data is not accessible to the outside known until the time of the call at run time. It is associated with polymorphism and
world, and only those functions which are wrapped in the class can access it.
inheritance. A function call associated with a polymorphic reference depends on the
Inheritance :
dynamic type of that reference.
Inheritance is the process by which objects of one class acquired the properties of objects of
another classes. It supports the concept of hierarchical classification. Message Passing:

Objects communicate with one another by sending and receiving information


much the same way as people pass messages to one another.

The principle of data hiding helps the programmer to build secure


Reusabality:
program that can not be invaded by code in other parts of a programs.
classes can be used by other classes. All objects oriented programming language can create returned and
Delegation: reusable parts of programs.
Provided reusability based on the relationship. Input and output in C++
Genericity: -Stream is a flow of data in bytes in sequence.
More than one version. -If input data is received from input device in sequence is
called as source stream.
Advantages of OOP:
-When the data is passed to output devices then its called
OOP offers several benefits to both the program designer and the user. Object
Destination stream.
Orientation contributes to the solution of many problems associated with the development
and quality of software products. The new technology promises greater programmer
Predefined streams:
productivity, better quality of software and lesser maintenance cost. The principal cin - standard I/P
advantages are: cout - standard O/P
Through inheritance, we can eliminate redundant code extend the use of existing clog - control error messages
Classes.
I/P Functions: cout \
cin cout cout c++
get() put() getch();
getline() write() }
read() flush()
peck()
ignore() 2).
g cout #include<iostream.h>
Sample programs:
#include<conio.h>
1).
#include<iostream.h> void main ()
#include<conio.h> {
Void main ()
clrscr():
{
Clrscr(); int a=10;
int b=10;

int c; cout value


c = a+b; cin>>b;
c=a/b;
cout<<c; cout of ;
getch(); cout<<c;
getch()
} }
Output:
3).Division of 2 numbers: Enter the value of a=20
#include<iostream.h> Enter the value of b=10
Division of two no. =2
#include<conio.h> 4).Average of 2 numbers:
#include<iostream.h>
Void main () #include<conio.h>
{ Void main ()
{
clrscr(); clrscr();
int a,b,c; int a,b;
Float c;
cout<< Enter the value of a= ; cout
cin>>a;
cin>>a;
5).Display the Name
#include<iostream.h>
cout value
cin>>b; #include<conio.h>
c=(a+b)/2 ; void main ()
cout {
cout<<c; char name[10];
getch(); clrscr();
} cout
Enter the value of a=100 cin>>name;
Enter the value of b=50 cout
Average of a and b =75.0
getch();
}
Output:
Enter the name kalam
Your name is kalam

Formatted console I/O Operations:


c++ supports a number of features that could be used for formatting the Setting Precision: precision() :
output. The features include: We can specify the number of digits to be displayed after the decimal point
width() while printing the floating point numbers.
precision() Syntax :
fill() cout.precision(d);
setf() is the number of digits to the right of the decimal point.
unsetf()
width(): To specify the required size for displaying an output value Filling and Padding: fill()
precision(): To specify the number of digits to be displayed after the decimal
point of a float value. The unused positions of the field are filled with white spaces .However, the fill()
fill(): To specify a character that is used to fill the unused portion of filled. function can be used to fill the unused positions.Where character represents the
character which is used for filling the unused positions.
setf(): The setf() method is used to set various flags for formatting
setf() :
output.
The setf() member function of the ios class is used for various types of
unsetf() : The unsetf() method is used to remove the flag setting. formatting.
Syntax:
cout<<setf(arg1, arg2);
The argument is one of the formatting flags, specifying the action
required for the output.
The argument known as bit field which specifies the group to flag meaning
which the formatting flag belongs.
ios :: showbase Use base indicator on output
There are three bit fields and each has a group of format flags.
ios :: showpas Print + before positive number
Formatting Flags, Bit-fields and setf():
Consider the following segment of code: ios :: showpoint Show trailing decimal point and zeros
cout.fill('*'); ios :: uppercase use uppercase letters for hex output
cout.setf(ios: :left, ios::adjustfield); ios :: skipus skip white space on input
cout. width(15); ios :: unitbuf flush all streams after insertion
cout ios :: studio flush stdout and stderr after insertion

Will produce the following output:


TABLE 1 * * * * * * * * * * *

Unformatted 1/O Operations :


getline() and write () Functions :
* cin and cout are the two predefined streams of input and output of
data.The operator << (insertion operator)is overloaded in the output The getline() function reads a whole line of text that ends with a newline
stream and >> (Extraction operator) operator is overloaded in input character.
stream.unformatted functions are as follows This function can be invoked by using the object cin.
* put() *get() * getline() *read() * write() functions cin.getline (line, size);
cin.getline(name,10);
put() and get () Functions : The function getline() which reads character input name with the size10.
The classes istream and ostream define two member functions get() The reading is determinated as soon as either the new line character is read or
and put() to handle the single character input and output operations. size-1 characters are read.
There are two types of get() functions:
Parts of the c++ program is as follows
get (char)
Include fields
get (void). Class definition or declaration
get(char ) version assigns the input character to its argument. Class function definition
get(void) version returns the input character. Main() function
TOKENS:
The smallest individual units in program are known as tokens. C++ has
the following tokens.
i. Keywords ii. Identifiers iii. Constants iv. Strings v. Operators
C ++ Data Types :
Both C and C++ compilers support all the built in types. With the
exception of void the basic datat ypes may have several modifiers
preceding them to serve the needs of various situations. The modifiers
signed, unsigned, long and short may applied to character and integer
basic data types. However the modifier long may also be applied to
double.
USER DEFINED DATA TYPES: CONTROL STRUCTURES:
-Like c, c++ supports all the basic control structures and implements
STRUCTURE AND CLASSES them various control statements.

We have used user defined data types such as structure and union in C. While these Decision making statements:
more features have been added to make them suitable for object oriented The if statement:
programming. C++ also permits us to define another user defined data type known as The if statement is implemented in two forms:
class which can be used just like any other basic data type to declare a variable. The 1. simple if statement
class variables are known as objects, which are the central focus of OOPs. 2
ENUMERATED DATA TYPE: Simple if statement:
An enumerated data type is another user defined type which provides a way for
if (condition)
attaching names to number, these by increasing comprehensibility of the code. The {
enum keyword automatically enumerates a list of words by assigning them values action;
0,1,2 and soon. This facility provides an alternative means for creating symbolic. }

If.. else statement


if (condition)
Statment1;
else Jumping Statements:
Statement2; The jump statement unconditionally transfer program control
The switch statement within a function. C language provides us multiple statements
This is a multiple-branching statement where, based on a condition, the control is transferred to
one of the many possible points;
through which we can transfer the control anywhere in the
Switch(expr) program.
{
case 1:
There are basically 3 Jumping statements:
action1;
Break; Jumping statements
case 2: continue statement
action2;
break;
goto statement
..
..
default:
message
}
Break satement: Syntax:
The syntax for a break statement in C is as follows:
-Sometimes, it s necessary to exit immediately from a loop as soon as the
Break;
conduct satisfied
The break statement in the programming language has the
-The break statement terminates the execution of the enclosing loop or following two usages:
statement. In a loop statement, the break statement can stop the counting when 1. When the break statement is encountered inside a loop. the
given condition becomes true. loop is immediately terminated and program control resumes
at the next statement following the loop
-The break statement is a jump instruction and can be used inside switch
2. can be used to terminate a case in the switch statement.
construct, for loop. while loop and do-while loop.
#include <stdio.h>
-The execution of break statement causes immediate exit from the concern #include <conio.h>
construct and the control is transferred to the statement following the loop. void main()
-In the loop construct the execution statement further execution of the program {
is reserved with the terminates loop and further execution of the program
reserved with the statement showing the day .

Continue :
int ;
for(i-0; i<100; i++) The continue statement provides a convenient way to force an
{ immediate jump to the loop control statement. The break
If i==10) break; // terminate loop if i is 10 statement terminates the execution of the loop.
printf("i: %d \n", i);
As you can see in the given example, we have used both the
{
statements within the do while loop. The program prompts the
printf "Loop complete.");
} user to entire any number. after number is less than 0, the break
statement terminates the execution of the loop. If the number is
greater than 10, the continue statement
skips the value and jumps to the do while loop without
terminating the loop. Otherwise, it will print the entered number.
continue :
1.Skips the remaining statements in the body of a while, for or
do/while structure .Proceeds with the next iteration of the loop
2.while and do/while Loop-continuation test is evaluated
immediately after the continue statement is executed .
3. for structure Increment expression is executed, then the loop-
continuation test is evaluated .
goto Statement:
It is a welknown as jumping statement.It is primarily used to
transfer the control of execution to any place in a program. It is
useful to provide branching within a loop.

When the loops are deeply nested at that if an error occurs #include <studio.h>
then it is difficult to get exited from such loops. Simple #include <conio.h>
break statement cannot work well properly. ln this void main()
situations. goto statements used. A goto statement in C {
programming language provides an unconditional jump int a;
from the goto lo a labeled statement in the same function. start :
Syntax: printf any
goto Label; scanf &a);
if(a<0);
goto start; //Goto statement A
a=a*a;
Label: statement; printf \n %d", a);
getch();
}
Loops in C++ Example:
For
#include <iostream>
While
using namespace std;
Do while
int main()
For loop:
Syntax: {
for (initialization; condition; update) for (int i = 1; i <= 5; ++i)
{ {
//body of-loop cout << i << " ";
} }
initialization - initializes variables and is executed only once
return 0;
condition - if true, the body of for loop is executed if false, the for
loop is terminated }
update - updates the value of initialized variables and again checks the
condition

While loop: The Do/While Loop:


The while loop loops through a block of code as long as a specified condition is true: The do/while loop is a variant of the while loop. This loop
Syntax: will execute the code block once, before checking if the
while (condition) condition is true, then it will repeat the loop as long as the
{
// code block to be executed condition is true.
}
Example: Syntax:
#include <iostream> do {
using namespace std; // code block to be executed
int main()
}
{
int i = 0; while (condition);
while (i < 5) { Example:
cout << i << "\n";
The example below uses a do/while loop. the loop will always be
i++;
} executed at least once, even if the condition is false because
return 0;
}
FUNCTION IN C++ :
the code block is executed before the condition is tested:
Example: The main( ) Function :
#include <iostream> ANSI does not specify any return type for the main ( ) function which is the
using namespace std; starting point for the execution of a program . The definition of main( ) is :-

main()
int main()
{ {

int i = 0; //main program statements


do }
{
This is property valid because the main () in ANSI C does not return any value. In
cout << i << "\n";
C++, the main () returns a value of type int to the operating system. The functions
i++;
that have a return value should use the return statement for terminating. The main ()
}
while (i < 5); function in C++ is therefore defined as follows.
return 0;
}

int main( ) That is the compiler replaces the function call with the
{ corresponding function code.
-------------- The inline functions are defined as follows:-
-------------- inline function-header
return(0) {
} function body;
Since the return type of functions is int by default, the key word
int in the main( ) header is optional. }
INLINE FUNCTION:
Example: inline double cube (double a)
To eliminate the cost of calls to small functions C++ proposes a {
new feature called inline function. An inline function is a function return(a*a*a);
that is expanded inline when it is invoked . }
The above inline function can be invoked by statements like
c=cube(3.0); d=cube(2.5+1.5);

remember that the inline keyword merely sends a request, not a command to the //Declaration
compiler.
int add(int a, int b); //prototype 1
The compiler may ignore this request if the function definition is too long or too
int add (int a, int b, int c); prototype 2
complicated and compile the function as a normal function.
double add(double x, double y); //prototype 3
FUNCTION OVERLOADING:
double add(double p , double q); //prototype4
Overloading refers to the use of the same thing for different purposes . C++ also
permits overloading functions .This means that we can use the same function name //function call
to creates functions that perform a variety of different tasks. This is known as cout<<add(5,10); //uses prototype 1
function polymorphism in oops. Using the concepts of function overloading , a cout<<add(5,10,15); //uses prototype 2
family of functions with one function name but with different argument lists in the
cout<<add(12.5,7.5); //uses prototype 3
functions call .The correct function to be invoked is determined by checking the
cout<<add(15,10.0); //uses prototype 4
number and type of the arguments but not on the function type.

For example an overloaded add() function handles different types of data as shown
below.
Object oriented programming with C++
Class and object

The class is used pack data and function.


UNIT-II:
The class Can be accessed only through objects .
Class and object: Declaring objects- Defining member functions-
The member variable and function are divided into two
Static Member functions- Array of object- friend functions-
section:
Overloading member functions-Bit Fields and class- Constructor
*private
and Destructor: Characteristics calling Constructor and
Destructors- Constructor and Destructors with static member *public

The object can not be access the private variables and function Example:
directly. #include<iostream.h>
It can be accessed only by the public member function. #include<conio.h>
Syntax: Class add
class class-name {
{ Private;
Private: int x,y,z;
Declaration of variables; Public:
Declaration of functions; Void sum()
Public: {
declaration of variables; Cin>>x>>y;
declaration of functions; z=x+y;
}; }
void display() Declaring object:
{ The declaration of object is same as declaration of variables.
cout<<z;
Object are created when the memory is allocated.
}
Accessing class members:
};
void main() The object can be accessed the public member variable and function
{ using the operator.
add a1; Syntax:
a1.sum(); Object name[operator] member name;
a1.display(); Example:
a1.add();
getch();
a1.add();
}

Public keyword void main()


{
The member variable and function can be accessed when it is declared as public. add a1.;
Example:
a1.x=10;
#include<iostream.h>
#include<conio.h> a1.y=20;
Class add a1.sum();
{
a1.display();
Public:
int x,y,z; getch();
void sum() }
{
};
z=x+y;
} Void add::sum()
void display() {
{
cin>>x>>y;
cout<<z;
} }; z=x+y;
}
Member function inside the class
void add::display()
{
count<<z; Member function inside the class can be declared in public (or)
} private section.
void main() The public member function can access the private member of
{
the same class.
add a1.;
a1.sum(); The member function that can be declared as public can be
a1.display(); accessed outside the class.
getch();
}

#include<iostream.h>
cin>>sno;
#include<conio.h>
cout
Class student
cin>>sname;
{
cout
Private:
cin>>m1>>m2>>m3;
int sno,m1,m2,m3,Total;
}
char sname[20];
void total_mark()
Public:
{
void getstudent()
total=m1+m2+m3;
{
}
Cout
void print _details()
{ Private member function:
cout
cout<<sno;
It is also possible to declare private function inside the class.
cout The private member function can be accessed only by the
cout<<sname; public member function.
cout
cout<<m1<<m2<<m3; It can be accessed like a normal function.
cout<<total; Example:
}
} #include<iostream.h>
void main() #include<conio.h>
{
student s1; {
s1.getstudent();
s1.total _mark();
Private:
s1.print _details(); int sno,m1,m2,m3,total;
getch();
} Char sname[20];

void init() void print details()


{ {
Sno=0,m1=0,m2=0,m3=0,total=0; cout
} cout<<sno;
Public : cout
Void get student() cout<<sname;s
init(); cout
{ cout<<m1<<m2<<m3;
Cout cout<<total;
cin>>sno; }
cout }
cin>>sno; void main()
cout {
cin>>sname; student s1;
cout s1.getstudent();
cin>>m1>>m2>>m3; s1.total mark();
} s1.print details();
void total mark() getch();
{ }
total=m1+m2+m3;
}
Member function outside the class: Public:
void get_student();
The function defined inside the class can be considered as inline
void total_mark();
function.
void print_details();
If a function is small it should be defined inside the class. };
If the function is large it must be defined outside the class. void student::get_student()
Example: {
#include<iostream.h> cout
cin>>sno;
#include<conio.h> cout
Class student cout<<sname;
{ cout
Private: cin>>m1>>m2>>m3;
}
int sno,m1,m2,m3,total; void student::total_mark()
Char sname[20]; {
total=m1+m2+m3;
}

void student::print_details()
{ Characteristic of Member Function
cout student
cout<<sno;
cout student
cout<<sname; The Difference between member and normal function is that
cout T normal function can be invoked freely where as the member
cout<<m1<<m2<<m3;
cout function can be accessed only by the object of the class.
cout<<total;
} The same function can be used in any number of classes.
};
void main() The private data (or) private function can be accessed by
{
Student s;
public Member Function.
s.get_student();
The member function can be accessed one another without
s.total_marks();
s.print_details(); using any object (or) . (dot) Operator.
Getch();
}
Outside member function inline
Example:
The inline mechanism reduces the overhead relating to access the #include<iostream.h>
#include<conio.h>
member function .
Class add
It provides better efficiency quick execution of function. {
Private:
Inline Function similar to Macros .call to inline function in the program int a,b,c;
places the function code in the caller program. Public:
Void get _in();
This is known as inline expansion.
Void sum();
Rules for inline function Void Print();
};
Use inline function rarely.
Void inline add:: get_in()
Inline function can be used when the member function contains few {
cin>>a>>b;
statement.
}
If a function takes more time to executed than it must to declared as
inline.

Void add:: sum()


{
Member Function inside the class
c=a+b;
} #include<iostream.h>
Void add:: print() #include<conio.h>
{ Class employee
Cout<<a<<b; {
Cout<<c; Private:
} int eno,ename,des,sal,bpay,hra,ma,pf;
Void main() Public:
{ Void get _employee()
add a1; {
a1.get_in(); Cout
a1.sum(); Cin>>eno;
a1.print(); Cout
} Cin>>ename;
Cout
Cin>>des; Cout
Cout Cout<<des;
Cin>>salary; Cout
Cout Cout<<salary;
Cin>>bpay; Cout B
} Cout<<bpay;
Void total_salary() }
{ };
Salary=hra+bp+ma-pf Void main()
} {
Void print_details() Employee E1;
{ E1.get_employee();
Cout T E1.total_salary();
Cout<<eno; E1.print_details();
Cout T getch();
Cout<<ename; }

Example:
Static member Variables & Functions Static int a;
Static void display();
Static member Variables:
int sumnum::a=0;
If a member variable is declared as static only one
-Sumnum is a classs name
copy of the member is created for the whole class.
The Static member variable is to be defined outside the class declaration.
The static is a keyword used preserve the value of the
variable. The reason for defining outside the class

Syntax: 1. The static data member or associated with the class not with the object.

Static<Variable definition> 2. The Static data members are stored individually rather than an element
Static<function definition> of an object.
3. The static data member has to initialize.
4. The memory for static data is allocated only once.
int number::C=0;
5. Only one copy of static member variable is created for the whole
int main()
class.
{
Example:
number a,b,d;
#include<iostream.h>
#include<conio.h> a.count();
Class number b.count();
{ d.count();
Static int c;
Public: }
Void count() Static member function:
{
Like member variables functions can also be declared as Static.
++c;
cout<<c; When a function is static it can access only static member variables
} and functions of the same class.
};

4. It is also possible to invoke static member function using object.


The non-static members are not accessed by the static member 5. When one of the object changes the value of data member variables the
effect is visible to all object of the class.
functions. Example:
The static keyword makes the function free from the individual #include<iostream.h>
#include<conio.h>
object of the class and its scope global in the class. Class number
The following rules has to be maintained while declaring the static {
Static int c;
function Public:
1. Only one copy of the static member is created in the memory for Static Void count()
{
the entire class. ++c;
2. Static member function can access only static data members and }
static void display()
function. {
3. Static member functions can be invoked using class name. cout
}
};
int number::c=0; Static Private member Function
int main()
Static member function can also be declared as private.
{ The private static function can be access using static public
function.
number::count(); Example:
#include<iostream.h>
number::display();
#include<conio.h>
number::count(); Class bita
{
number::display(); Private:
static int c;
} static void count()
Public:
Static void display()

{
count(); Static public member variable
cout \
}
The static public member variable can be initialized outside the class
}; and also can be initialized in the main function.
void bita ::c=0; It can be initialized like a normal variable.
void main() Example:
{ #include<iostream.h>
clrscr(); #include<conio.h>
bita::display(); int c=11;
bita::display(); Class bita
}
{
Output: value of C:1
Public:
Static int c;
value of C:2
};
Static Object
int bita::c=22;
void main() The object is a composition one or more variables. The
{ keyword static can be used to initialize all class data members
to zero.
clrscr();
Declaring object as static will initialize all the data members to
int c=33; zero.
cout \ bita::c; Example:
cout \ #include<iostream.h>
cout \ #include<conio.h>
Class number
}
{
Output:c=22
int c,k;
c=11
Public:
c=33

Array of Object
void plus() Array is a collection of similar data types it can be of any data type including user
{
defined data type created by struct,class,type,def declarations.
c=c+2;
k=k+2; We can also create an array of objects.
} The array elements of stored in continuous memory location.
void show()
The arrays can be initialized or accessed like an ordinary array.
{
cout<<c; Example:
cout<<k; #include<iostream.h>
} #include<conio.h>
Class student
void main()
{
{
int Sno;
static number x;
char sname[20];
x.plus(); Public:
x.show(); void get_input();
} void display();
Output : c-=2 }
k=2
Void main()
void student::get_input()
{
student s[10];
{
int n, i;
cout
cout no.of.students
cin>>sno;
cin>>n;
cout for(i=1;i<=n;i++)
cin>>sname; {
} s[i].get_input();
void student::display() }
{ For(i=1;i<=n;i++)
cout<<sno; {
cout<<sname; s[i].display();
} }
}

2. Pass by reference
Objects as Function arguments
Address of the object is implicitly sent to function.
Like variables objects can also pass to functions. 3. Pass by address
There are three methods to pass an arguments:
Address of the object is explicitly sent to function.
1. Pass by value
In this type a copy of an object is sent to function and In pass by reference and pass by address methods the address of the
assigned to object of calling function . actual object is passed to the function.
Both actual and formal copies are objects are stored in
different memory location so changes made in formal So, duplicating of the object is prevented.
objects does not reflect to actual object.
Cout \
Example: Cin>>expyr;
#include<iostream.h> }
#include<conio.h> Void period(life);
};
Class life Void life::period(life yr)
{ {
int mfgyr; yr=y1.expyr-y1.mfgyr;
cout
int expyr; }
int yr; void main()
Public: {
clrscr();
Void getyrs() life a1;
{ a1.getyrs();
cout a1.period(a1);
}
cin>>mfgyr;

Friend Function
1. There is no scope restriction for the friend function . So they
can be called directly without using objects.
Any non-member function has no access permission to the 2. Friend function cannot access the member directly . It uses
private data of the class. object and dot operator to access the private and public
The private member of the class are accessed only from the member.
member function of that class. 3. By default friendship is not shared that is if class x , if
C++ allows a mechanism in which a non-member function has declared as friend of class y. It does not mean y has rights to
access permission to the private members of the class. access private member of class x.
This can be done by declaring a non member function friend to 4. Use of friend function is rarely done because it violets rule of
the class whose private data is to be accessed. encapsulation and data hiding.
Here friend is a keyword 5. The function can be declared as public (or) private without
The friend function have the following properties: changing its meaning.
Example:
class first
#include<iostream.h>
{
#include<conio.h>
int f;
class first;
public:
class second
void get value()
{
{
int s;
public:
cin>>f;
void get value() }
{ friend void sum(second ,first);
cin>>s; };
} void sum(second d, first t)
friend void sum(second,first); {
}; cout<<t.f+d.s;
}

Friend Classes
void main()
{
It is possible to declared one or more functions as friend
first a;
second b; function or entire class can be declared as friend class.
a.get value();
The friend is not transferable or inheritable one class to
b.get value();
sum(b,a); another .
}
The friend classes are applicable when we want to make
available private data of a class to another class.
Example: Class B
#include<iostream.h> {
#include<conio.h> int b;
class B Public:
void get B()
class A
{
{
b=40;
int a; }
public: friend void A:: show(B bb);
void get A() };
{ void A:: show(B bb)
a=30; {
} cout<<a;
void show(B); cout<<bb.b;
}; }

Void main()
Overloading member function

{
Member functions are also overloaded in the same way as
A.a1; ordinary functions.
Overloading is nothing but one functions is defined with
B.b1; multiple definition with same function name.
a1.getA(); Example:
#include<iotstream.h>
b1.getB();
#include<conio.h>
a1.show(b1); #include<stdlib.h>
#include<math.h>
}
Class absv
{
Public: int main()
int num(int);
double num(double);
{
}; clrscr();
int absv::num(int x)
absvn;
{
int ans; cout \n Absolute value of - -25);
ans=abs(x); cout \n Absolute value of - -25.1474);
return(ans);
} return 0;
double absv:: num(double d) }
{
double ans;
ans=fabs(d);
return(ans);
}

Constructor & destructor The constructor may contain arguments to pass the values to
the function.
When a variable is declared and if it is not initialized it A program may contain one or more constructor.
contains garbage value. Constructors are also called when local or temporary objects of
The compiler itself cannot initialize the variable the program a class are created.
explicitly assign a value to the variable. Characteristics of Constructor
CONSTRUCTORS 1. Constructor has the same name as the class name.
The constructor constructs the object. Constructors are special 2. Constructor is executed when an object is declared.
member functions 3. Constructor have neither return value nor void.
When an object is created constructor is executed. 4. The main function of constructor is to initialize objects.
The constructor are automatically executed when the objects 5. Constructors are executed implicitly and they can be invoked
are created. explicitly.
6. Constructor can have default and can be overloaded. 4. The destructor is automatically executed when an object goes out of
7. The constructor without arguments is called default construtor. scope.
5. It is also invoked when delete operator is used to free the memory
DESTRUCTOR
allocation.
1. Destructor are special member function used to destroy the 6. Destructors are not overloaded.
object. 7. The class can have only one destructor.

2. The destructor is executed at the end of the function or at the Characteristic of destructor

end of the program. 1. Destructor has the same name as that of the class it belongs to and
proceeded by ~(tilde)
3. The destructor can be defined same as class name preceded
2. Like constructor, the destructor does not have return type and not
with ~(tilde) operators. even void.

3.Constructor and destructor cannot be inherited, though a 8. TURBO C++ compiler can define constructor and destructor if

derived class can call the constructor and destructors of the they have not been explicitly defined. They are also called on

base class. many cases without explicit calls in program. Any constructor

4. Destructor can be virtual, but constructors cannot. (or) destructor created by the compiler will be public.

5.Only one destructor can be defined in the class. The destructors 9.Constructor and destructors can make implicit calls to operators

not have any argument. new and delete if memory allocation/de-allocation is needed
for an object.
6. The destructor neither have default values nor can be
overloaded. 10. An object with a constructor or destructor cannot be used as a
member of a union.
7. Programmer cannot access addresses of constructors and
destructors.
void calculate()
{
Example: s=a+b;
#include<iostream.h> }
void display()
#include<conio.h>
{
class sum cout<<a<<b;
{ cout<<s;
int a,b,s; }
public: ~sum()
sum() {
{ cout
s=0; }
} };
void getdata() void main()
{
{
sum.s1;
cin>>a>>b; s1.getdata();
} s1.calculate();
s1.display();
}

Constructors with arguments {


a=x;
b=y;
}
Void calculate()
It is also possible to create constructors with arguments and such {
s=a+b;
constructors are called parameterized constructor. }
Void display()
For this type of constructor it is necessary to pass value to the {
constructor when the object is created. cout<<a<<b;
cout<<s;
Example: }
~sum()
#include<iostream.h> {
cout
#include<conio.h> }
};
Class sum Void main()
{
{ Sum s1=sum(3,4);//explicit
Sum s1(3,4);//implicit
int a,b,s; S1.calculate();
S1.display();
Public: }
sum(int x, int y)
Depending upon the number of arguments the compiler
Overloading Constructor executes the appropriate constructor.
Example:
It is also possible to overload constructors. #include<iostream.h>
#include<conio.h>
Constructors may contain arguments or may not contain arguments.
class sum
A class can contain more than one constructor. {
int a,b;
This is known as constructor overloading. float c,d;
All constructors are defined with the same name as the class. public:
sum(int x, int y)
All the constructor contain different number of arguments. {
a=x;
b=y;
}

Sum(float x1,float y1)


{
c=x1; void main()
d=y1; {
}
void display() sum s1=sum(3,4);
{ s1.display();
cout<<a<<b;
cout<<c<<d; sum s2=sum(5.5,10.5);
} s2.display();
~sum()
{ }
cout
}
};
Using copy constructor it is possible for the programmer to
Copy Constructor declare and initialize one object using reference of another
object.
The constructor can accept argument of any data type including Whenever the constructor are called the copy of object is
user-defined data type. created.
Example:
It is possible to pass reference of object to the constructor. #include<iostream.h>
This declaration is known as copy constructor. #include<conio.h>
class num
In this type a temporary copy of the object is created.
{
All copy constructors require one arguments with reference to an int a;
object of that class. public:
num(){}
num(int k)

{
a=k; Destructors
}
num(int x)
{ It will destroy the object. Destructors is also a special member
a=x.a;
}
function like constructor.
void show()
{
It destroy the class object created by constructor.
cout<<a;
The destructors have the same name as the class name
}
}; proceeded by ~(tilde)operator.
void main()
{ For local and non-static object the destructor is executed when
num n(10);
num(n); the object goes out of scope. It is not possible to define more
n.show(); than one destructor.
c.show();
} Destructor releases memory location occur the memory object.
Example:
#include<iostudio.h> Constructor and destructor with
#include<conio.h> static members
class num
{
int a; Every object has its own set of data members.
public:
num() When a member function is called only copy of data is
{
cout available to the function.
}
~num() Sometimes it is necessary for all the object to share the data
{
cout field which is common for an object.
}
}; If the member variable is declared has static.
void main()
{ Only one copy of the member is created for entire class.
num n1;
}

The static member variable used to count number of object for cout<<no;
a particular class. }
Example: ~man()
{
#include<iostudio.h>
--no;
#include<conio.h> }
class man };
{ int man::no=0;
static int no; void main()
{
char name;
man A,B,C;
int age; cout
public: }
man()
{
no++;
OBJECT ORIENTED PROGRAMMING WITH C++ 3.1 Operator Overloading
SUB CODE :18BIT23C

UNIT III: Operator Overloading: Overloading Unary Binary Overloading is an important feature of c++
Operators Overloading Friend Functions Type Conversion It is similar to function overloading. An operator is a symbol
Inheritance: Types of Inheritance Single Multilevel Multiple used for an operation.
Hierarchical Hybrid and Multi Path Inheritance Virtual Base C++ has the ability to treat the user-defined data type.
Classes Abstract Classes.
As a built in data type.
TEXT BOOK The Operator + can be used to perform addition of two
1. Ashok N Kamthane variables but it is not possible to perform addition of two
Education Publications, 2006. objects.
Operator overloading is one of the most valuable concept to
perform this type of operation.
Prepared By: Dr. M. Soranamageswari It is a type of polymorphism permit to write multiple
definitions for functions and operators.

Example

The Operator +,-,* and = are used to carry the operations of Number operator +(number D)
overloading. {
The Capability to relate the existing operator with a member Number T;
function and use the resulting operator with object of its class, T.X=X+D.X;
as its operands is called Operator Overloading.
T.Y=Y+D.Y;
Syntax:
Return T;
Return type
}
{
S+1
S+2
}
Overloaded Operators are redefined using the keyword The prototype for operator overloading can be
Operator followed by an Operator symbol. return as follows:
An Operator function should be either a member function or Void Operator ++();
Friend function. Void Operator - -();
A Friend Function requires one argument for unary operators Void Operator ();
and two for binary Operators.
Num operator + (num);
A Member function requires one argument for binary operator
and no arguments for unary Operators. Friend num operator * (int, num);
Void Operator =(num);

Example:

The Prototype of operator overloading function in classes. #include<iostream.h>


The Operator Overloading can be carried out in the following #include<conio.h>
steps: class number
{
Define a class to be used for overloading operations.
public:
In the public section the class contains the prototype of the int X;
function operator(). int Y;
Define the definition of the operator() number() {}
number (int j, int k)
{
X=j;
Y=k;
}
number operator +(number D) void main()
{ {
number T; clrscr();
T.X=X+D.X; number A(2,3) ,B(4,5),C;
T.Y=Y+D.Y; A.show();
Return T; B.show();
} C=A+B;
void show() C.show();
{ }
cout \ \
}
};

3.2 Overloading Unary Operators


num(int j, int k, int m, int l)
{
The Operator ++, - - and or unary Operator. a=j;
The unary Operator ++ and - - can be used as prefix and suffix with b=k;
the functions.
c=m;
These operators have only one operand.
d=l;
Example:
}
#include<iostream.h>
void show(void);
#include<conio.h>
void operator ++();
class num
};
{
void num::show()
private:
{
int a,b,c,d;
cout
public:
}
void num:: operator ++()
{ ++a;++b;++c;++d;}
3.3 Overloading binary operator:

void main() Overloading with a single parameter is called binary operator


{ overloading
clrscr(); Binary operators requires two operands binary operator or
num X(3,2,5,7); overloaded using member function and friend function
cout \ Overloading binary operator using member function:
X.show(); Overloading binary operator using member function require 1
argument
++x;
The argument contains value of the object which is to the right
cout \ of the operator
X.show(); The overloading function should be declared as follows.
return 0;
}

Syntax: Example:
Operator(num 02); 03=01 operator + (02)
Where, The callingunction can be written as,
03=01+02
Operator is a symbol
Here the data membr are passed to the called function and
Num is an class performs the number of addition based on number of
02 is the argument of the class arguments
Example: void num: :input( )
{
#include<iostream.h> cin >>a>>b>>c>>d;
#include<conio.h> }
class num void num : :show( )
{
{ cout <<a<<b<<c<<d;
int a,b,c,d; }
num : : operator+(num t)
public: {
void(input(void); m tmp;
tmp.a=a+t.a;
void show(void); tmp.b=b+t.b;
num operator + (num); tmp.c=c+t.c;
tmp.d=d+t.d;
};
return(tmp);
}

3.4 Overloading friend functions


Friend function are more useful in operator overloading
void main ( ) They are more flexible then member function,
{ The different between member function and friend function is
num x,y,z; that member function arguments explicitly
x.input( ); The friend functions needs the param eter should be explicitly
y.input ( ); fast.
z=x+y; Friend function requires two operands to be passed as
arguments
x.show( );
Syntax
y.show( );
Friend return type operator (variable!, operator symbol
z.show( );
variable?)
}
{

}
Example:
friend num operator + (num n1 num n2) num operator*(inta, numt)
#include <iostream.h> {
#include<conio.h> num tmp;
class num tmp.a = a*t.a;
{ tmp.b = b*t.b;
int a,b,c,d ; tmp.c = c*t.c;
public: tmp.d = d*t.d;
void input (void); return(tmp);
void show (void); }
friend num operator*(int,num); void main( )
}; {
void num : : input( ) num x,z;
{ x.input( );
cin >>a>>b>>c>>d; z=3*x;
} x.show( );
void num : : show ( ) z.show( );
{ }
cout<<a<<b<<c<<d;
}

3.5 Type conversion

The constants and variable of various data types are S.no Conversion type Routine in Routine in source
companied in a single expression can be automatically destination class class
converted by the compiler. 1 class to class Constructor Conversion
function,
The compiler has no knowledge about the user-defined data
(operator
type and about their conversion of other data type. function)
There are three possibilities of data conversion. 2 class to Basic - Conversion
1. Conversion from Basic data type to user-defined data function,
(operator
type(class type)
function)
2. Conversion from class type to basic data type 3 Basic to Class Constructor -
3. Conversion from one class type to another class type
Conversion type.
3.5.1 Conversion from Basic class type

Basic source and destination objects are user defined data type
the conversion routine can be carried out using operator In this type the left hand operand of (=) equal sign if always
function is source class or using constructor in destination the class type. The right hand operand is always basic type.
class. The Conversion can be done by the compiler with the helpof
If the user defined object is destination class. The conversion build routine or by applying type casting.
routine should be carried out using constructor in the It uses constructors for changing the Basic type to class type.
destination class.
If the user defined object is a source object. The conversion
routine should be carried out using source object in the
operator function.

Example:
#include<iostream.h>
#include<conio.h>
class data void show( )
{ {
int x ;
float f; cout<<x<<f;
public: }
data( ) };
{
x=0; f=0; int main ( )
} {
data(float m) data= z
{
x=2; z=1;
f=m; z.show( );
} z= 2.5
z.show( );
}
3.5.2 Conversion from class type Basic data
type
The conversion function should not have any argument
The compiler does not have any knowledge about the Do not mention return type.
user defined data type using class. It should be a class member function.
In this type of conversion the programmer explicitly specify Example:
about the conversion. #include<iostream.h>
There instruction are return in a member function. This type of #include<conio.h>
conversion also known as over loading of type cast operators. class data
In this type the left hand operand is Basic data type the right {
hand operand is class type.
int x;
To perform this conversion it must satisfy the following
condition. float f ;

void show( )
public; {
data( ) cout<<x<<f;
{ }
X=0; y=0; };
int main( )
}
{
operator int ( )
int j;
{ float f;
return(x) ; data a;
} a=5.5;
data (float (m) j=a;
{ f=a;
x=2; cout<<j;
f=m; cout<<f;
}
}
3.5.3 Conversion from one class type _
another class type
public:
There are two ways to convert one class type to another class stock1 (int a, int b, int c)
type {
One is to define a conversion operator function in source class code =a;
or a constructor in a destination class. item =b;
Example: price =c;
#include<iostream.h> }
#include<conio.h> void disp( )
class stock2: {
{ cout<<code;
int code, item; cout<<item;
float price; cout<<price;
}

int getcode( ) operator float()


{ {
return(item*price);
return code;
}
} };
int getitem() class stock2
{ {
return item; int code;
float val;
}
public:
int get price() stock2()
{ {
return price; code=0;value=0;
} }
stock2(int x,float y)
{
code=x;
val=y; void main()
} {
void disp()
stock 1 i1(10,10,100.5)
{
cout<<code; stock i2;
cout<<val; Float tot=i1;
} i2=i2;
stock2(stock1 p) i1.disp();
{
i2.disp();
code=p.getcode();
val=p.getitem()*p.getprice(); }
}
};

3.5.4 Rules For Overloading Operators


Overloading of an operator cannot change the basic idea of an
operator. when an operator is overloaded. its properties like A=A+B
syntax, precedence, and associativity remain constant. Overloading of an operator must never change its natural
Example: meaning.
A and B are objects. An overloaded operator+ can be used for subtraction of two
A+=B objects. but this type of code decrease the utility of the
program.
Assigns additions of objects A and B to A. The overloaded
operator must carry the same task the original operator Remember that the aine of operator overloading is to comfort
according to the language. the programmer to carry various operations with objects.
The floating statement must perform the same operation like
the last statement.
3.6.1 Access specifies and simple inheritance:
3.6 Inheritance The public members of a class can be accessed by objects,
It is one of the most useful characteristic of object oriented programming. directly outside the class.
New classes are created from existing classes.
The private members of the class can be accessed by public
The properties of existing classes are extended to new classes.
member function of the same class.
The new classes are called are derived classes.
The existing classes are known as base classes. The protected access specified this same as private.
The term reusability means to reuse the properties of base class in the The only difference is that it allows its derived classes to
derived class. access protected members directly with out member function.
Reusability is achieve using inheritance the outcome of inheritance is Syntax:
reusability.
The base class is called is called super class or parent class or ancestors
Derived class
class. Class name of derived class:access specifier name of the base
The derived class is called as sub class or child class or descendent class. class
It is also possible to derive a class from previously derived class. {
A class can be derived from more than one class.
Member variables of derived class
}

Example: 3.class B:protected A


1.class B:public A {
{ .
. .
. }
} 4.class B:A(default definition private)
2.class B:private A {
{ .
. .
. }
}
3.6.2 Public inheritance

1. When public access specified is used public members of the A class can be derived publicly or privately.when a class is
derived class. similarly the protected members of the base derived publicly all the public members of the base class can
class or protected member of the derived class. be accessed directly in the derived class.
The public derivation does not allow the derived class to
access private member variables of the base class.
2. When a private access specified is used public and protected
members of the base class or private members of the derived
Example:
class.
Write a program to derive a class publicly from base
class.declare the base class with its member under public
section.
#include<iostream.h>
#include<conio.h>

Class A void main()


{ {
Public: clrscr();
Int X; B b;
}; b.x=20;
Class B:public A b.y=10;
{ \ b.x;
Public: \ b.y;
Int Y; }
};
3.6.3 Private inheritance
Class B:private A
The object of privately derived class cannot access the public {
members of the base class directly. Public:
The member function are used to access the member of the base Int y;
class. B()
Example: {
Write a program to derive a class privately. Declare the member X=20;
of base class under public section. Y=40;
#include<iostream.h> }
void show()
#include<conio.h>
{
class A
cout \
{ cout \
public: }
int x; };
};

3.6 4 Protected data with private inheritance

void main() The member functions of derived class cannot access the
{ private member variables of base class.
clrscr(); The private members of base class can be accessed using
B b; public member functions of the same class.
b.show(); To overcome this problem the protected access specifier is
used.
}
The protected is same as private but it allows the derived class
to access the private members directly.
Example:
void shows( )
#include<iostream.h>
#include<conio.h> {
class A cout \
{
cout \
protected:
int x; }
}; };
class B:private A
void main( )
{
int y; {
public: clrscr( )
B( )
B.b;
{
x=30; b.show( );
y=40; }
}

The types of inheritance are as follows:


3.7 Types of Inheritance

The process of inheritance can depends on the following 1.Single inheritance or simple
points. 2.Multiple inheritance
1.Number of base classes: 3.Hierarchical inheritance
The program may contain one or more base classes. 4.Multilevel inheritance
2.Number of derived classes: 5.Hybird inheritance
A program may contain one or more derived classes. 6.Multipath inheritance
Example:
3.8 single inheritance: #include<iostream.h>
#include<conio.h>
When only one base class is used for derivation of a class and Class ABC
the derived class is not used for base class. {
protected:
Inheritance between one base class and one a derived class is char name[20];
known as single inheritance. int age;
The new class is termed as derived class and the old class is };
class abc:public ABC
called base class. {
A Derived class inherit data members and member functions float height,weight;
of base class. public:
void getdata()
The Constructor and destructor of base class are not inherited. {
cin>>name>>age;
cin>>height>>weight;
}

3.9. Multiple Inheritance

Two or more base classes are used for derivation of a class.


void display() That is this type of inheritance contains one or more base
{ classes and a single derived class it is known as multiple
inheritance.
cout<<name<<age;
When a class is derived from more than one base class is
cout<<height<<weight;
known as multiple inheritance.
};
Properties of various base classes are transferred to single
void main() derived class.
{
abc x;
x.getdata();
x.display();
}
Example: class C
#include<iostream.h> {
#include<conio.h> protected:
class A int z;
{
}
protected:
int x: class D: public A,B,C
} {
class B int d;
{ public:
protected:
void getdata()
int y;
} {
cin>>x>>y>>z>>d;
}

3.10.Hierarchical inheritance

void display() A single base class is used for derivation of two or more
{ derived classes is known as hierarchical inheritance.
cout<<x<<y<<z<<d; Inheritance also support hierarchical arrangement of programs.
} Hierarchical unit source the top down arrangement of classes.
};
void main()
D.d1;
d1.getdata();
d1.display();
}
class C
Example:
#include<iostream.h> {
#include<conio.h> protected:
int z;
class A
}
{
protected: class D: public A,public B
int x; {
int d;
}
public :
class B
void getdata()
{
protected: {
int y; cin>>x>>y;
}
}

void get()
{
cout<<e<<z;
void display() }
{ };
cin<<x<<y; void main()
} {
}; E e1;
class E:public D,public C e1.getdata();
e1.display();
{ e1.get();
int e; e1.put();
public: }
3.11 Multilevel inheritance
void put()
When a class is from another derived class that it the derived
{
class act is a base class.
cout<<age<<name;
This type of inheritance is known as multilevel inheritance.
cout<<height<<weight;
Example:
cout<<sex;
#include<iostream.h>
}
#include<conio.h>
};
class A1
void main()
{
{
protected :
A3.x;
int age;
x.get();
char name[20];
x.put();
};
}

class A2:public A1
{ 3.12 Hybrid Inheritance
protected:
float height;
The combination one or more type of inheritance is known as
float weight;
hybrid inheritance.
};
class A3:publc A2 Here two types of inheritance is used. That is single and
{ multiple inheritance.
protected: x-base class
char sex; y-derived class and base class of z.
public: w-base class
void get()
{
cin>>age>>name;
cin>>height>t>weight;
cin>>sex;
}
class A4:public A2,A3
Example: {
#include<iostream.h> protected:
#include<conio.h> char address[20];
Public:
class A1
void get( )
{
{
protected: cin>>age>>name;
int age; cin>>height>>weight;
char name[20]; cin>>sex;
}; cin>>address;
class A2:public A1 }
void put( )
{
{
protected:
cout<<age<<name;
float heirght; cout<<height<<weight;
float weight; cout<<sex;
}; cout<<address;
class A3 }
{ };
void main( )
protected:
{
char sex;
A4 x;
}; x.get( );
x.put( );
}

3.13.Multipath Inheritance: Example:


#include<iostream.h>
#include<conio.h>
When a class is derived from two or more classes which are {
derived from the same base class is called multipath protected:
inheritance.
int age;
It consists of many types of inheritance such as Multiple,
char name[20];
Multilevel, Inheritance.
};
x-base class
class A2:public A1
y, z, w-derived classes of x.
{
y, z-base class for w.
protected:
float height;
float weight;
};
class A3:public A1 void put( )
{ {
protected:
char sex; cout<<age<<name;
}; cout<<height<<weight;
class A4:public A1,A2,A3 cout<<sex;
{
protected: cout<<address
char address[20]; }
public: };
void get( )
void main( )
{
cin>>age>>name; {
cin>>height>>weigjht; A4 x;
cin>>sex;
x.get( );
cin>>address;
} x.put( );
}

{
protected:
3.14 Virtual base class int age;
char name[20];
};
To overcome the ambiguity occurd in multipath inheritance class A2:public virtual A1
c++ provides the keyword virtual. {
The keyword virtual declares the specified classes as virtual. protected:
float height;
It can avoid the duplication of member variables defined in the float weight;
base classes. };
Example: class A3:public virtual A1
{
#include<iostream.h> protected:
#include<conio.h> char sex;
};
class A1 class A4:public A2,A3
{
protected:
char address[20];
Public:
void get( )
{
cin>>age>>name; void main( )
cin>>height>>weight;
{
cin>>sex;
A4.x;
cin>>address;
} x.get( );
void put( ) x.put( );
{ }
cout<<age<<name;
cout<<height<<weight;
cout<<sex;
cout<<address;
}};

protected:
3.15 Abstract classes int age;
When a class is not used for creating object is called abstract char name[20];
classes. };
class abc:public ABC
The abstract classes can act as a base class. It is the layout
{
abstraction in a program and it allows the base class on several
float height,weight:
levels of inheritance.
public:
An abstract classes developed only to act as a base class for void get data( )
inheriting the properties and no object of these classes are {
declared. cin>>age>>name;
Simple inheritance cin>>height>>weight;
Example: }
#include <iostream.h> void display( )
{
#include<conio.h>
cout<<age<<name;
class ABC cout<<height<<weight;
{ } };
void main( )
{
abc x;
x.get data( );
x.display( );
}
OBJECT ORIENTED PROGRAMMING WITH C++ Pointer and arrays:
SUB CODE :18BIT23C

UNIT IV: Pointers: Declaration Pointer to Class Object THIS Pointer C++ variables are used to hold data during program execution.
Pointer to Derived Classes and Base Classes Arrays: Characteristics Arrays Every variable can occupy some memory location to hold the
of Classes Memory Models New and Delete Operators Dynamic Object data.
Binding Polymorphisms and Virtual Functions.
Memory is arranged in a sequence of byte.
TEXT BOOK The number specification to each byte is called memory
1. Ashok N Kamthane address.
Education Publications, 2006
The sequence starts from 0 onwords.
It is possible to access and display the address of memory
Prepared By: Dr. M.Soranamageswari
location using the pointer variable.

Feature of pointer:
Pointer:

Pointer is a memory variable that store a memory address. Pointer save memory space.
Pointer can have any name that is legal to other variable. Execution time with pointer is faster.
It can be declared like normal variable it is always denoted by The memory is accessed efficiently with the pointer.
star(*)operator. Pointer are used with data structure and they are useful for
representing two dimensional array.
A pointer declared to a base class can access the object of
derived class.
Pointer Declaration:

Pointer can be declared as follows: It inform to the compiler that hold the address of any variable.
Syntax: The in-direction(*)operator is also called de-reference
Data type * pointer variable name. operator.
Where as a pointer indirectly access to their own values.
Example: The (&) is the address operator represented the address of a
int *a; variable.
int *b; The address of any variable is a whole number.
float*c;

Example: Void pointer


Display the value and address of the variable using pointer. Pointer can be also be declared as void type.
#include<iostream.h> Void pointer cannot be reference without explicit type
#include<conio.h> conversion.
void main() A void pointer can pointer any type of variable with proper
{ type casting.
int *p; Example:
int x=10; #include<iostream.h>
p=&x; #include<conio.h>
cout<<x<<&x; int p;
cout<<*p<<&p; float d;
} char c;
void *pt=&p;
void main()
Pointer to class:
{
*(int*)pt=12; The pointer is a variable that hold the address of another data
variable.
cout<<p;
The variable may be of int,float and double in the same way
pt=&d; we can define pointer to class.
*(float*)pt=5.4; This type of pointer are called class pointers.
cout<<d;
pt=&c; Syntax:
Class name *pointer variable name
cout<<c;
} Example:
Student *str;

Example: Voidputdata()
{
#include<iostream.h> cout<<name<<age;
#include<conio.h> }
Classman };
{
public: void main()
char name[20]; {
int age; Man *ptr,m;
voidgetdata(char s[10],int a) ptr=&m;
{ ptr->getdata );
name =s; ptr->putdata();
age=a; }
}
Pointer to object: Example
#include<iostream.h>
#include<conio.h>
Like variable object can also have an address.
class bill
The pointer can point to a specified object. {
Using the pointer it is possible to access different type of intqty;
classes. float price;
float amount;
Syntax: public:
{
Class name*ptr variable name;
Voidgetdata(inta,floatb,float c)
{
Eg: qty=a;
Student*str; price=b;
amount=c;
}

void show()
{ This pointer:
cout \
cout \
cout \ The objects are used to invoke non static member function of
} the class.
}; The pointer this is transferred as an unseen parameters to call
int main() non static member function.
{ The keyword is a local variable always present in the
clrscr(); body of non-static member function.
bill s;
The keyword this does not need to be declared.
bill*ptr;
ptr=&s; The pointer is rarely referred explicitly in a member function.
ptr->getdata(45,10.25,45*10.25); It is used implicitly with in the function for member reference.
(*ptr).show(); Using this pointer it is possible to access the individual
return 0; member variables of the object.
}
void show()
Example: {
Program to use this pointer and return pointer cout<<num;
reference(minimum or smallest value of two numbers) }
#include<iostream.h> number min(number t)
#include<conio.h> {
Class number if(t.num<num)
{ return t;
Public: else
intnum; return *this;
void input() }
{ };
cin>>num;
}

Pointer to derived classes and base class :-

void main() It is possible to declare a pointer , which points to the base


{ class as well as the derived class.
number n,n1,n2; One pointer can point different classes.
n1.input();
n2.input(); Example
n=n1.min(n2); Write a program to declare a pointer to the base class and
n.show; access the member variable of base and derived class.
} # include<iostream.h>
#include<conio.h>
class A
{
Public:
void main()
int b;
{
void display() clrscr();
{ A*CP;
cout \ A base;
CP=&base;
} CP->b=100;
}; // CP->d=200;Not accessible
class B:public A cout \n CP points to the base object\
CP->display();
{ B b;
public: Cout \n CP points to the derived class\
int d; CP=&b;
CP->b=150;
void display()
// CP->d=300; Not accessible
{ CP->display();
cout \ \ return 0;
}
}
};

Pointer to the derived class

#include<iostream.h> class B : public A


#include<conio.h> {
class A public:
{ int d;
public: void display()
int b; {
void display() cout \ \ \ \
{ }
cout \ };
}
};
Array

void main() Array is the collection of elements of similar data types in


{ which each element in unique and located in separate memory
clrscr(); locations.
B*CP; Array declaration and initialization:-
B b; The arrays can be declared for different data type are described
as follows;
CP=&b;
int a[10];
CP->b=100;
char b[20];
CP->d=350;
double c[5];
cout \n CP points to the derived object \
The array initialization can be declared as follows:-
CP->display();
return 0;
}

Example Example
int a[5]={1,2,3,4,5};
The range of elements begins from zero(0) memory location. #include<iostream.h>
Characteristics of arrays :- #include<conio.h>
All the elements of an array of the same name and they are differentiated
class arraytest
from one another with the help of elements number.
The element number in an array is the most important factor in calling each {
element. int a[10];
Any particular element of an array can be modified without disturbing the public:
other element.
Any element of an array can be assigned to another ordinary variable (or) void get();
array variable of its type. void display();
The array elements are stored in continuous memory locations, the amount };
of storage required for the elements depends on its type and size
Total bytes=sizeof( data type)*sizeof(array)
void arraytest::get()
{
for(int i=1;i<=10;i++)
{ void main()
cin>>a[i];
{
}
arraytest a1;
}
a1.get();
void arraytest::display()
{
a1.display();
for(int i=1;i<=10;i++) }
{
cout<<a[i];
}
}

Example
Array of classes :- #include<iostream.h>
#include<conio.h>
An array is a collection of similar data type in the same way it Class student
is also possible to define array of classes.
{
Here array is a class type array of class object can be declared
Char sname[20];
as follows:
Char grade;
class student
int sno;
{
Public:
char sname[20];
void get();
student s[10];
void display()
int sno[10];
};
char sadr[20];
}
void student::get()
{
void main()
cin>>sname;
{
cin>>sno; student S[10];
cin>>grade; int n,i;
} cout
cin>>n;
void student::display()
{ for(i=1;i<=n;i++)
cout<<sname; {
cout<<sno; S[i].get();
}
cout<<grade;
for(i=1;i<=n;i++)
} {
S[i] display();
}
}

The different types of memory models used in


C++ and Memory models :-
C++ are as follows :
1. Tiny :-
The memory models sets the supportable size of code and data.
The tiny model is absolutely premium all four segment
Before computing and linking the source code we have to registers(CS,DS,SS,ES) are initialized with same address and all
specify the appropriate memory model. addressing is accomplished using 16-bits total memory capacity
C++ always use different segments for code and data. is 64 kb.
The code data and stack must fit with in the same 64kb segment
Programme are executed quickly is this model is selected.
2. Small :-
All code should fit in a single 64kb segment.
All pointers are 16bit in length execution speed is same as single
model.
This model is used for average size programs near pointers are
always used.
3. Medium :- 5. Large :-
All data fit in a single 64kb segment. Both code and data allowed to multiple segment.
The code is allowed to use multiple segments. All pointers are 32bits code execute is slow.
All jumps and calls require 32bits address. This model is preferred for very big programs.
In this model access to data is passed program execution is For pointers are used for both code and data.
slowwith their model. 6. Huge :-
Far pointers are used for code. Both code and data are allowed to use multiple segments
4. Compact :- Every pointers is 32bits in length cod execution is the slowest.
All code fit in 64kb segment to the data can use multiple The huge model permits multiple data segments 1MB code
segment all pointers to data and 32bits. segments and 64kb for stack.
But jumps and calls used 16bits slow action to data and quick
code execution will be observed this model.
For pointers are preferred for data.

The pointers and code pointers are far

S.no Memory Secments Type of 5 Large 1mb 1mb Far Far


model pointers 6 Huge 1mb 64kb 64kb Far Far
each

Code Data Stack Code Data

1 Tiny 64kb 64kb Near Near

2 Small 64kb 64kb Near Near

3 medium 1mb 64kb Far Near

4 Compact 64kb 1mb Near Far


7. Segment and offset address New operator :-
Every address has to parts segment and offset these parts are
defined using two macrosdefind in <dos.h> header file.
The new operator allocates memory of specified type and
FP-SEG()-this macros is used to obtained segment address. returns the starting address to the pointers memory variable.
FP-OFF() this macros is used to obtained offset address. If fails to allocate its returns null value.
Syntax
The new and delete operators Pointer memory variable=new data type
C++ provide new and delete operators can be used for crating Example
and destroying the object.
a= new int;
int *a = new int[50];
*a = new int[3];

Delete operator :-

The delete operator frees the memory location allocated the Size of operator
operators. The sizeof operator is used to returns the size of your variable
bytes.
Syntax
Delete pointer variable name; Syntax
Delete [element size] pointer variable name; sizeof (variable name);
Example
Delete a; Example
Delete[50] a; Cout<<sizeof(a);
Few points regarding : new and delete
operators are :-
The new operator not only creates an object but also allocates The statement delete x does not destroy the pointer x.
memory. It destroy the object.
The new operator allocates correct amount of memory from If the object created is not deleted it occupy the unnecessarily.
the heap that also called a free store. It is a good habit to destroy the object and release the system
The object created and memory allocated using new operator resources.
should be deleted by the delete operator.
The delete operator not only destroys the object but also
returns the allocated memory.
The new operator creates an object and its remains in the
memory until it is released using delete operator.
If we sent a null pointers to delete operator it is secure using
delete to zero(0) has no result.

Difference between new and malloc()

Write a program to allocate memory to store 3 integers. Use new


New Malloc() and delete operator.
#include<iostream.h>
Creates objects Allocates memory
#include<conio.h>
returns pointers of relevant returns void pointer.
int main()
type. Malloc() cannot be
It is possible to overload new overloaded. {
operators. Clrscr();
inti,*p;
p=&i;
Dynamic object:-

p=new int[3]; C++ supports dynamic memory allocation .C++ allocates


*p=2; memory and initializes the member variable.
*p(p+1)=3; An object can be created at run time.
*p(p+2)=4; such object is called dynamic.
cout The construction and destruction are dynamic object is
explicitly done by the programmer.
for(int x=0;x<3;x++)
The operator new and delete are used to allocate and
cout<<endl<<*(p+x \ p+x); deallocate to such objects.
delete[]p; A dynamic objects can be create using new operator.
return 0; Syntax:
} Ptr=new class name;

Example
#include<iostream.h>
#include<conio.h>
The new operator returns the address of the object created and
class data
it is stored in the pointer(ptr).
{
Ptr is a pointer variable is the same class.
int x,y;
The member variables of object can be accessed using operator
public:
The dynamic object can be destroy using delete operator.
data()
{
Syntax:
cout \
delete ptr;
x=10;
It destroy the object pointed by pointer ptr.
y=50;
}
~data(){cout \
void display()
{
cout \ Binding ,polymorphism and virtual functions
cout \ Binding:-
} In c++ functions can be bound either at complied time (or) at
}; run time designing the function call at compile time is called
void main() compile time (or)early(or)static binding.
{ Designing function call at run time is called as run
clrscr(); time(or)late(or)dynamic binding .
data*d; Dynamic binding permits the decision of choosing suitable
d=new data; function until run time.
();
delete d;
}

Static or early binding:-

Similar function name are used at many places but during their int k;
references their position is indicates explicitly . public:
Their ambiguities are fixed at compile time. void display()
Example: {
class first cout<<k;
{ }
int d; }
public:
void display()
{cout<<d;}
};
2. Dynamic (or) late binding :
Example:
#include<iostream.h>
Dynamic binding of member function in c++ can be done
#include<conio.h>
using the keyword VIRTUAL
class data
The member function followed by virtual keyword is called as
virtual function. {
The virtual function must be defined in public section. int x,y;
If the function is declared virtual,the system will use dynamic public:
binding data()
Which is carried out at runtime {
cout \
x=10;
y=50;
}

~data() void main()


{ {
cout \ clrscr();
} data*d;
void display() d=new data;
{ ();
cout \ delete d;
cout \ }
}
};
Polymorphism:

It is a technique in which various forms of single function can Polymorphism:


be defined and shared by various object to perform the
operation polymorphism

Run time Compile time

Function
Virtual function Operator overloading
overloading

Rules For Virtual Function:


Virtual Function The virtual function should not be static and must be a number of
class
Run time polymorphism can be achieved using virtual A virtual function may be declared as friend for another class
functions Constructors cannot declare as virtual but destructors can be
Virtual functions of the base class must be re-defined in the declared as virtual
derived class The virtual function must be defined in public section of the class
The virtual keyword is used in the declaration and not in the
member declaration
A virtual function in a base class can use the same function
It is also possible to return a value from virtual function
name in any derived class even if the number and type of
The prototype of virtual function in base and derived should be the
argument of same Virtual functions can be number functions
same
Arithmetic operation cannot be used with base class pointer
If a base class contains Virtual function and if the same function is
not redefined then the base class function is invoked
The operator keyword is used for operator overloading also supports
virtual mechanism
Example:
#include<iostream.h> virtual void display()
#include<conio.h> {
class first
cout<<d;
{
}
int b;
public: };
first() { b=10; } void main()
virtual void display() {
{
first f,*p;
cout<<b;
} second s;
}; p=&f;
class second: public first ();
{
p=&s;
int d;
();
public:
second() { d=20; } }

Array of pointers virtual void show()


{
Polymorphism refer to late (or) dynamic binding. cout
Dynamic binding is associated with object pointers. }
Address of different object can be stored in an array to invoke };
the function dynamically.
class B : public A
Example
{
#include<iostream.h>
public:
#include<conio.h>
void show()
class A
{
{
cout
public:
}
};
public:
void show()
class C : public A {
{ cout
public: }
void show() };
{ class E : public A
cout {
} public:
}; void show()
class D : public A {
{ cout
}
};

Pure virtual function :-


void main()
{ The member function of the class is rarely used for doing any
A a; operation.
B b; Such function are called do-nothing functions, dummy
C c; function or pure virtual function.
D d; The pure virtual function are always virtual function.
E e; There are defined with null body after declaration of pure
A*P[]- { &a,&b,&c,&d,&e}; virtual function in a class. The becomes abstract class.
for(int i=0;i<5;i++) It cannot be used for declare any object.
{
P[i] ->show();
}
}
#include<iostream.h>
The pure function can be declared as follows: #include<conio.h>
class first
{
Syntax protected;
virtual void display()=0; int b;
A pure virtual function declared in base class cannot be used public:
for any operations. first(){b=10}
The class containing pure virtual function cannot be used virtual void display()=0;
declared object. };
Class second : public first
Such class are known as abstract class (or) pure abstract class.
{
The class is derived from pure abstract classes are required to int d;
redeclared pure virtual function. public:
All other derived classes witout pure virtual function are called second(){d=20}
concreate classes. void display(){ cout \nb \
These classes can be used to create objects. }

Constructor and virtual function

int main() It is possible to define a virtual function using constructor.


{ Constructor makes the virtual mechanism illegal.
clrscr(); When a virtual function is invoked throw a constructor the
first*P; base class virtual function will not be called and instead of this
second *S; member function of the class is invoked.
p=&S; Example
p->display(); #include<iostream.h>
return 0; #include<conio.h>
} class B
{
int k; public :
public:
B(int l) D(int m,int n):B(m)
{ {
K=1;
} h=n;
virtual void show() B=*b;//base class ptr in derived class constructor
{
cout<<k;
B this;//it contains the address of the object calling the member
} fun.
}; b->show();
class D : public B
{ }
int h;

Virtual destructors

void show() Destructors can also declared as virtual.


{ Constructors cannot be virtual since it requires about the
cout<<h; accurate type of object.
} Destructors of derived and base class are called when a
}; derived class object is addressed by the base class pointer is
deleted.
void main()
When the base class pointer is destroy using delete operation
{ the destructors of base and derived class is executed.
B b(4);
D d(5,2);
}
virtual ~B()
}
cout
Example };
#include<iostream.h> class D:public B
#include<conio.h> {
public:
class B
D();
{
{
public:
cout
B(); }
{ ~D()
cout {
} cout
};

void main()
{
B*P;
P=new D;
delete P;
}
OBJECT ORIENTED PROGRAMMING
WITH C++ Applications With Files:
SUB CODE :18BIT23C
UNIT V: Files: File Stream Classes File Modes Sequential Read/ Write The file is an accumulation of data stored on the disk created by the user.
Operations Binary and ASCII Files Random Access Operation The programmer assigns the file name, the file names are unique and are
Command Line Arguments - Exception Handlings : Principles of used identify the file. No two files can have the same name in the same
Exception Handling The Keywords try, Throws and Catch Exception directory.
Handling Mechanism Multiple Catch Statements Catching Multiple There are various types of files such as text file, program file, data file and
Exceptions Re-throwing Exception Strings: Declaring and Initializing executable files.
String Objects Strings Attributes Miscellaneous Functions.
Data files constrain a combination of number, alphabets, symbols etc.,
Data communication can be performed between program and output
TEXT BOOK devices or files and programs.
1. Ashok N Kamthane, Oriented Programming with ANSI and File stream are used to perform the communication.
Turbo Pearson Education Publications, 2006.
The Stream is nothing but flow of data in bytes in sequence.
The input stream brings data to the program and the output stream collect
data from the program..
Prepared by: Dr. M.Soranamageswari

File Buffer
5.1 File Stream Classes: File Buffer used to accomplished input and output operations with
files.
The io functions of the class istream and ostream invoke the file-buf
Stream is nothing but flow of data..In oops the streams are controlled using function to perform the insertion and extraction on the streams.
classes.
The operations with the files are mainly of two types Fstream Base
There are read and write. It act as a base class for fstream, ifstream and ostream classes.
The ios class is the base class all other classes are derived from ios class.
This classes contain several member function to perform input and output
operation. Ifstream
The istream and ostream classes control input and output functions It is derived from fstream base class it can access the member
respectively. function such as get(), getline(), seekg(), tellg() and read().
The function get(), getline(), read() and >> or defined in the istream class.
The function put(), write() and << are defined in the ostream class. Ofstream
The class ifstream and ofstream are derived from istream and ostream This classes derived from fstream base and ostream class.
classes respectively.
It can access the member function such as put(),seekp(), tellp() and
The header file fstream.h contains the declaration of ifstream and ofstream write().
classes.
Fstream
File Name:
It allows simultaneous input and output operations on a file buffer.
The file name can be a sequence of characters called as streams.
FSTREAM invoke the member function getline() to read() the
characters from the file. String are always declared with character array using file name a file
is recognized.
Steps of File Operations
The length of file depends on the operating system.
The file operation invokes the following basic activities
Normally it is eight characters.
1. File name
A file name also contain extension of 3 characters.
2. Opening file
The extension is optional
3. Reading (or) writing file
Svcc.txt
4. Detecting error
Prg.cpp
5. Closing the file
Test.tat

5.2 File Opening modes:


The opening of file involves several modes depending upon the
Opening file: operation to be carried out with the file.
There are two methods for opening a file The open() function has two arguments
Constructor of the class 1. File name
Member function open() 2. File mode
Syntax:
Constructor of the class: Object.open filename:filemode ;
The file stream object is created using suitable class and initialized
with the file name. Example:
The constructor itself uses the file name as the first argument and Out.open text.dat:ios::out);
opens the file.
The file can be opened with one or more mode parameters.
The class of stream creates the output stream object and ifstream
When more than one parameter necessary the bitwise operator
creates the input stream object.
separates them. It does not create a new file if the specified file is
not present.
in.open ::in::ios::binary);
Example: char ch;
Out.open ios::nocreate) while(in.eof()==0)
Write a program to open a file in a binary mode write and read the data. {
#include<iostream.h> ch=in.get()
#include<conio.h> cout<<ch;
#include<fstream.h> }
void main() }
{
ofstream out; Finding End Of A File:
char name[20]; While reading a data from a file.
out.open ::out::ios::binary) It is necessary to find the end of the file. The programmer predict the end of
the file.
cin.getline(name,20);
The program does not detect then if will be the infinite loop.
out<<name;
So avoid this it is necessary to provide to detect the end of file.
out<<close();
EOF() member function is used for this propose.
ifstream.in;

It is an instruction given to the program by the operating system of end of


the file is reached. File Pointers And Manipulators
The EOF() function returns zero value when end of file is detected.
otherwise zero.
To file pointers are associated file .
Example: This to file pointers provide two integer values.
#include<iostream.h> The read or write operations are carried out using these file pointers.
#include<conio.h> The get pointers helps to read the file from the given location.
void main() The put pointers helps for writing data in file at a specified location.
{ While file is open the for reading or writing the file pointers are at the
char c; beginning of the file.
ifstream So the reading and writing can be performed from the beginning of the file.
while(in.eof()==0) To explicitly set the file pointer at the specified position the file function
are used.
{
in.get(c); Read Mode:
cout<<in.eof(); When a file is open in read mode the get pointer is set at the
}
beginning of the file.
} It reads the file from the first characters of the file.
File Pointers Managing Function:

Write Mode: Seekg()


It is the member of ifstream() class.
When a file is open write mode the put pointers is set of the It shift the input pointer to a given location.
beginning of the file. Seekp()
In case the specified file already exists the content of the file It is the member of ofstream class.
will be edited. It shift the output pointer the given location.
Uppend Mode: Tellg()
It is the member of ifstream class.
When a file is open in upend mode. It provides the current position of the input pointer.
The output pointers is set at the end of the file. Tellp()
When a pre existing file is successfully opened in uppend It is the member of ofstream class.
mode the contains remains safe and new data is upended of the It provides the current position of the output pointer.
end of the file.

Manipulators With Arguments 5.3 Sequential Read And Write


The seekp() and seekg() function can be used with two
arguments. C++ allows file manipulations command to accessed a file
Example: sequentially or randomally. The data of sequential files must
Seekg(offset, preposition) be access one characters at a time.
Seekp(offset,preposition) To access thus specified by all the previous characters are read
and ignored.
The first arguments offset specifieds the number of bytes the
file pointer is to be shifted from the argument preposition of There are member of function to perform read and write
the pointer. The preposition arguments have the following operations.
values. The put() and get() functions are used to read or write a single
The seekg() function shift the associated files input file character. The read() and write() block of binary data.
pointers.
The seekp() function shift the associated files output pointers.
The Put() And Get() Functions:
The functions get() reads a single characters from the file. io.open data;ios::in/ios::out);
Pointered by the get() pointer. \
The put() function writes a character to the specified file. io.put(text[1++]);
Example:
io.seekg(0);
#include<fstream.h>
char c;
#include<conio.h>
#include<string.h>
cout \
int main() while(io)
{ {
clrscr(); io.get(c );
char text[50]; cout<<c;
cout \ }
cin.getline(text,50); return 0;
int i=0; }
fstream io;

The Read() And Write() Functions: int main()


{
The read() and write() function is used binary format of dat during clrscr();
operation. intnum[]={100,105,110,120,155,250,255};
In binary format the data representation is same in the file and the ofstream out;
system. out.open
The binary form follows quicks read and write because know out.write((char*)&num,size of (num);
conversion is needed during the operations.
out.close();
The format a read() and write() function is follows:
for(int i=0;i<7;i++)num[i]=0;
Syntax:
ifstream in;
In.read((char *)&p,size of(p));
in.open
Out.write((char *)&p,size of (p));
in.read((char *)&num,size of (num);
Example:
for(i=0;i<7;i++)cout<<num[i \
#include<fstream.h>
return 0;
#include<conio.h>
}
#include<string.h>
5.5 Random Access Operation
5.4 Binary And Ascii Files:
Random access operation data file always contain large information always
changes.
ASCII codes are used by the io devices to share the data to the The changed information should be updated.
computer system. To update a particular record or data file it may be stored any ware in the
The CPU can process only the binary numbers(0,1) file but it is necessary identify in the location where the data object is
stored.
So it is the essential to convert the data while accepting the The size of() operator determines the size of the object.
input device and display the data to the output device. Error Handling Functions
Example: There are many reasons to cause error during reading or writing operation
cin>>a; of the program.
An attempt to read a file which does not exist
cout<<a;
The file name specified for opening a new file may already exist.
The Operator<<converts the integer value into a stream of An attempt to read the file when the file pointer is at the end of the file.
ASCII characters. The operator>>convert the ASCII value of Insufficient disk space
the binary format and assign it to the variable.

5.6 Command Line Arguments

Invalid file name specified by the programmer. An executable program that performs a specific task for operating
system is called a command .
An attempt to write data to the file that is opened in read only The commands are issued from the command prompt of os.
mode. Some arguments are associated with command called as command
A file opened may already opened by another programs. line arguments.
These arguments are passed to the program.
An attempt to opened read only file for writing operation. In c++ every program start with a main() function.
Device error. The main()function does not contain any arguments
In command line arguments the main() function can receive two
arguments.
1.argc-argument counter it contains the number of arguments
2.argv-argument vector it is an array of character pointers.
Syntax:
in.open(argv[1],ios::in,ios::nocreate);
Main(int argc,char *argv[])
if(in.fail())
Example:
{
#include<stdio.h> cout \n file not found;
#include<fstream.h> exist(0);
#include<conio.h> }
#include<process.h> in.close();
main(int argc, char *argv[]) out.open(argv[2],ios::in,ios::nocreate);
{ if(out.fail())
fstream out; {
ifstream in; rename(argv[1],argv[2]);}
else
if(argc<3)
cout \
{
return 0;
cout
}
exist(1);
}

Definition Of Class Templates:


Generic Programming With Template: The class templates can be defined as follows:
The template provides generic programming by defining generic Syntax:
class. Template class<T>
In template generic data types are used as arguments and they can class classname
handle a variety of data type. {
A functions that works for all c++ data types is called as generic
function. }
Need For Template: Template class<T> specifies the compiler the following class
Template is a technique that allows using a single function or declaration use the template data type.
class to work with different data types. T is a variable of template type that can be used in the class to define
They can accept data of any type such as int, float,char,double variable of template type.
etc., One or more variables can be declared by unseparated by comma.
Templates allows better flexibility to the program and overcome Templates can not be declared inside classes are functions. They
the limitation of over loading function. must be global.
Example:
#include<iostream.h>
#include<conio.h>
Normal Function Template
template class<T>
class data A normal function can also used template arguments.
{ The difference between normal and member function is that
public: normal function are defined outside the class.
data( T C)
These are not members of any class.
{
cout \ They can be accessed directly without using (.) dot operator
}}; Syntax:
int main() Template class<T>
{ Function name()
clrscr();
{
data<int> i(100);
data<float> j(3.12); }
return 0; }

Example:
#include<iostream.h> Overloading Of Template Function:
#include<conio.h>
Template class<T>
void show(T x) A Template function also supports overloading mechanism.
{
It can be overloaded by normal function or template function
cout<<x;
} No implicit conversion is carried out in parameters of template
void main() function.
{ The rules are,
Search for accurate match of function, if found it is invoked
int i=100;
float f=10.5; Search for a template function with accurate match can be
show( c); generated if found it is invoked
show(i); Attempt normal overloading declaration for the function
show(f);
Incase of no match found error will be reported
}
# include< iostream.h >
#include < conio.h > Class Template With Overloaded Operator:-
template < class T >
The template class permits to declare overloaded operators and member
void show (T a)
function.
{
Creating overloaded operator function is similar to class template members
cout << a;
and functions.
}
#include<iostream.h>
void show (int x)
{ #include<conio.h>
cout <<x; #include<class T>
} class num
void main( ) {
} private:
tnumber;
show(10); public:
show(10.5); num()
}
{
number=0; }

void input()
{
cin>.number;
}
num operator +(num); void main()
void show()
{
{
cout<<number; num<int>n1,n2,n3;
} N1.input;
}; N2.input;
Template<class T>
num<T> num<T>::Operator+(num<T>) N3.show();
{ }
num<T> temp;
Tmp.number=number+c.number;
return(temp);
}
Class Templates And Inheritance:

The template class can also act as a base class. Syntax:


When inheritance is applied with template class it helps Template< class T>
to compose hierarchical data structure known as class XYZ
container class. {
Derive a template class and add new members to it.
The base class must be of template type. }
Derive a class from non-template class and add new
template type member to derived class.
It is also possible to derive classes from template base {
class and omit the template features of the derived
class. }

The name of template class is written differently in different situations,


Guidelines For Templates: while class declaration it is declared as follows:
Templates are applicable when we want to create type secure class
that can handle different data type with same member functions. void data<T>:: show(T d) { }
The template classes can also be involved in inheritance. show() is a member function
For Example: In the example, the template argument T is not used as a parameter and the
complier will report an error.
Template<class T>
Template<class T>
class data : public base<T>
void show(int y)
Both data and base are template classes. The class data is derived { T temp;}
from template class base. In the above example, template type arguments is not an
The template variables also allow us to assign default values. argument.possibily the system will crash.
For Example: Template<class T,class s>
Template<class T, int x=20> void max( T & K)
class data {SP;}
{ The template variables S in not used. Therefore, compile time error is
generated.
Tnum[x];
}
5.7 Exception Handling: 5.8 Principles Of Exception Handling:

While writing large programs a programmer makes many Exceptions are two types
mistakes developing an error free program is the objective of 1.synchronous exception
the programmer. 2.Asynchronous exception
Programmer have to take care to prevent errors. The goal of exception handling is to create a routine that detect and
Errors can be trapped using exception handling features. an exceptional condition is order to execute suitable action.
An Exception is an up normal terminator of a program, which The routine carries the following responsibilities:
is executed in a program at run-time or it may called at run- 1. Detect the problem
time when an error occurs the exception contains warning 2. Warning message indicates an error.
messages like invalid argument insufficient memory, division 3. Accept the error message.
4. Perform the accurate action.
An Exception is an object , it is sent from the part of the program
where an error occurs to that part which is going to control the error.

5.9 The Keyword try, throw and Catch


5.10 Exception Handling Mechanism:
The Keyword try
Exception handling technique possess the control of a program from a Exception handling Mechanism provides three keyword try, throw
location of exception in a program to exception handling routine linked and catch.
with the key block. The keyword try is used at the starting of the exception.
An Exception handling routine can be called by throw statement. The throw block is present inside the try block.
Try is a keyword contains series of statement. Immediately after the try block catch block is present.
The keyword throw When an exception is found the throw statement throws an
The function throw statement is to sent the exception found. exception(message) for catch block that an error has occurred in the
The throw statement can be placed in function or in nested loop and it try block.
should be in try block The catch block receives the exception and performs the actions.
After throwing exception control possess to the catch statement. Example:
The Keyword Catch Write a program to throw exception when j=1 otherwise perform the
Catch block also contains a series of statements. sub of x and y.
It also contains an argument of exception type..
#include<iostream.h>
#include<conio.h>
void main()
{
catch(int k)
int x,y;
cout {
cin>>x>>y; cout
J=x>y?0:1; }
try }
{
if(j=0)
{
cout<<x<<y;
}
else
{
throw(j); }}

5.11 Multiple Catch Statements: 5.13 Catching Multiple Exceptions :


We can also define multiple catch block in try block. It is also possible to define single caught block for one or more exception
It contains multiple throw statements based on certain conditions. of different types.
Syntax: Syntax:
try catch
{ {
Sts;
multiple throws sts;
}
}
catch(object 1)
{ Example:
catch section 1; #include<iostream.h>
} #include<conio.h>
catch(object 2) void num(int k)
{ {
catch section 2; Try
} {
catch(object n)
{
catch section n; }
if(k==0)
5.14 Re-throwing Exception
throw k;
else It is also possible to pass the exception received to another
if(k>0)
block and this is known as re -throwing exception.
throw p;
Syntax:
else
throw;
if(k<0)
The throw statement is used without any arguments.
throw 0;
Example:
} #include<iostream.h>
#include<conio.h>
{ void sub(int j, int k)
cout {
cout \n;
}
try
} {

try
if(j=0)
{
throw j; sub(8,5);
else sub(0,5);
cout - \ }
} catch(int)
catch(int)
{
{
cout \ cout \
throw; }
} cout \
cout \n\ getch();
}
int main()
}
{
cout \n inside function main()\
5.15 Declaring and Initializing String Objects: 4.Strcmp();
Example:
1. Strlen()
Srtcmp(str1,str2);
2. strcpy() 5)stricmp();
Syntax: Example
Strcpy(destination ,source) i=stricmp(Str1,Str2)
Example: 6)Strncmp();
Strcpy(b,a) Example
Set=strncmp(Str1,Str2,4);
3.strncpy
7)Strnicmp();
Syntax: Example
Char*strncpy(char*desk, const char *src, size t n) j=strnicmp(Str1,Str2,5);
Example: 8)Strlwr();
Strncpy(dest,src,10); Example
Strlwr(Str1);

13)StrStr()
9)Strupr();
Example:
Example
Strupr(Str1); Set=strstr(traystack,needle);
10)Strdup():- 14) strncat()
Example:
Example
Strncat
P2=Strdup(p1);
11) Strchar(); 15) strset()
Example Example:
Strset(str
Set=Strchr(Str,ch);
12) Strrchar();
Example
Set=strrchar(Str,ch);

You might also like