Object Oriented Programming With C - Ug1
Object Oriented Programming With C - Ug1
Object Oriented Programming With C - Ug1
PREPARED BY S.KALAISELVI/R.KANAKARAJ/R.LATHA
*****************************************************************
SUBJECT DESCRIPTION:
GOAL:
OBJECTIVE:
UNIT-I:
UNIT-II:
UNIT-III:
UNIT-IV:
UNIT-V:
Files: File stream classes – file modes – Sequential read / write operations – Binary
and ASCII Files – Random Access Operation – Templates – Exception Handling – String:
Declaring and initializing string objects – String Attributes – Miscellaneous functions.
REFERENCE BOOKS:
2. C++ PROGRAMMING Black Book, Steven Holzner, Wiley Student edition, Wiley
India.
3. DATA STRUCTURES USING C & C++, Yedidyah Langsam, Moshe J. Augenstein
&Aaron M. Tanenbaum, 2nd edition, PHI.
UNIT – I
The next standard version (known informally as C++0x, in reference to the long-
standing expectation that it would be released sometime before 2010) is in development; its
final draft was approved on March 25, 2011 and the formal specification is expected to be
published in the summer of 2011.
INTRODUCTION TO C++:
1. Object
2. Classes
3. Method
4. Data abstraction
5. Encapsulation
6. Inheritance
7. Polymorphism
8. Dynamic binding
9. Message passing
10. Reusability
Object
The selected program objects must be similar to real time objects. Objects occupy
space in memory. Every object has its own properties.
Class
A class is grouping up of objects having identical properties, common behavior, and
shared relationship.
Method
All objects in a class perform certain common actions or operations. Each action needs an
object that becomes a function of the class that defines it and referred to as a method.
Class a
private:
public:
method1();
Member function or method
method2();
};
Data Abstraction
Encapsulation
The packing of data and function into a single component is known as encapsulation.
Inheritance
Inheritance is the method by which objects of one class get the properties of an
another class.
In this example class B get the properties from the Class A same as C.
Fig 1. Types of Inheritance
Types of Inheritance
Simple inheritence
Multilevel inheritance
Hirarchical inheritence
Multiple inheritance
Hybrid inheritance
Polymorphism
Line
Display()
Fig 2: Polymorphism
Dynamic Binding
Message Passing
OOP includes objects which communicate with each other. Programming with these
objects should be followed in steps shown below:
Object object
. communication operator
display message
argument data
Reusability
OOP allows reusability of the classes by extending them to other classes using
inheritance. Once the class is defined, the other programmer can also use it in their
programs and add new features to the derived classes. The main advantage is it saves the
time.
Example:
In the following example class A reused and class B is created. Again class B is
reused and class C is created.
Class A
Class A
Real-time examples:
Class
Car Vs Class
Car: Collection of several properties like staring, break, clutch, etc each things are
used for particular purpose, all these properties are differ from each car like some car have
power staring ,however we have called it’s a car.
Class: it’s a collection of functions and variables. The functions and variables are
differing from each class. Each function is used for particular purpose however we have
called it’s a class
Object
Car Key: key is used for run the car. So many dummy keys can use for run a car.
Object: Object is used for run the class or invokes the class. So many objects can
create for a single class.
Birds Vs Abstractions
Birds: we invented flight based on the mechanism of Birds. So flight is derived form
the base of birds.
Pen Vs Encapsulation
Pen: Ink is the important component in pen but it is hiding by some other material
Encapsulation: is a process of binding or wrapping the data and the codes that
operates on the data into a single entity. This keeps the data safe from outside interface
and misuse. One way to think about encapsulation is as a protective wrapper that prevents
code and data from being arbitrarily accessed by other code defined outside the wrapper.
Crocodile Vs Polymorphism
Crocodile: live indifferently on land or in the water. In water it’s Moment very fast
compare to land. An animal lives in different character in different place.
Inheritance: The new classes, known as derived classes, take over (or inherit)
attribute and behavior of the pre-existing classes, which are referred to as base classes (or
Parent classes). It is intended to help reuse existing code with little or no modification.
ADVANTAGES OF OOP:
3. Using inheritance, redundant program codes can be eliminated and the use of
previously defined classes may be continued.
4. The technology of data hiding facilitates the programmer to design and develop
safe programs that do not disturb code in other parts of the program.
6. All OOP languages can create extended and reusable parts of programs.
C++
Smalltalk
Charm ++
Java
Smalltalk
Charm++
Java
I/O IN C++
Streams in C++
C++ supports a number of input/output operations to read and write operations. The
stream is an intermediator between I/O devices and the user.
Stream is flow of data In bytes in sequence. If data is received from input devices in
sequence is called source or input stream. When the data is passed to output devices then it
is called as destination stream or output stream.
Keyboard Monitor
Stream
Disk Disk
Fig 4. Streams and I/O devices
Predefined Streams
C++ has predefined streams. These streams are called as standard I/O objects.
These streams are automatically activated when the program execution starts.
cin standard input usually corresponding to stdin in c. it handles inputs from input
devices usually from keyboard.
Clog a fully buffered version of cerr. It controls error massages that are passed from
buffer to the standard error device.
Cerr standard error output corresponding to stderr in c. it controls the unbuffered
output data. It catches the error and passes to standard error device monitor.
#include<iostream.h>
#include<conio.h>
void main()
clrscr();
cout<<”\n streams”;
cerr<<”\nstreams”;
clog<<”\nstream”;
getch();
output:
streams
streams
streams
Stream Classes
C++ has a number of stream classes that are used to work with console and file
operations. These classes are called stream classes. All these classes are declared I the
header file iostream.h.
IOS
The fig describes isream and ostream are derived classes of base class ios. The class
contains member variable object streambuf. It places in buffer. Istream and ostream are
derived from ios class using inheritance concept. The classes istream_withassign,
ostream_withassign, iostream_withassign append appropriate assignment operators.
The input stream uses cin object to read data and the output stream uses cout
object to display data on the screen. The cin and cout are predefined streams for input and
output of data. The data type is identified by these functions using operator overloading of
the operators << and >>. The operator << is overloaded in the ostream class and the
operator >> is overloaded in istream class.
Input stream
Input stream does read operations through keyboard. It uses cin as object. The cin
statement uses >> before variable name.
Syntax :
cin>>variable;
Example :
int a;
cin>>a;
The operator >> accepts the data and assign it to the memory location of the
variable. Each variable requires >> operator.
Output Stream
The o/p stream manages output of the stream. It uses << insertion operator before
variable name. It uses the cout object to perform console write operation.
Syntax:
cout <<variable;
Example :
int n;
cout<<variable;
Type casting refers to the conversion of data from one basic type to another by
applying external use of data type.
#include<iostream.h>
#include<conio.h>
void main()
clrscr();
int x=77;
char y=’A’;
cout<<”x =”<<(char)x<<endl;
cout<<”y =”<<(int)y<<endl;
getch();
Output: x=M
y=65
123445338.33
cout<<(double) float to double
1.234453e+08
Signed to
cout<<(unsigned)-1; 65535
uunsigned.
C++ DECLARATIONS
Include files
main() function
C++ program depends upon the header files and function definition. Each header file
has an extension .h. the file should included using # include directive as per the format
given below:
#include<iostream.h> or #include”iostream.h”
All the definitions and prototypes of function defined in this file are current program.
This header file also gets complied with the original program. The header files are included
at the top of the program so that can be accessible from any part of the program.
We can also declare the class after the main function. But it is better to declare it
before main() function. Class definition is always terminated by a semicolon. Function
prototype declaration reports to the complier’s name, return type and required argument
list of the function.
The function definition can be done outside or inside the class. The function defined
inside the class are implemented as inline function.
Types of Tokens
The c++ programs contain various components. The components identify them as
tokens.
Keyword
Variables
Constants
Special character
Operators
Keywords
The c++ keywords are reserved words by the compiler and fixed meaning. There are
63 characters in c++ and turbo c++ permits 14 extra keywords. Some compliers won’t
accept variable names that exactly match to the keywords.
Identifiers are the names of variable, function and arrays etc, there are user defined
names, consisting of a sequence of letters and digits, with a letter as a first character.
Lower case letters are preferred. Upper case letters also permitted. The underscore symbol
can be used as an identifier.
Rules of identifier:
The identifier name must begin with a character and should not start with a
digit, no space between characters. Underscore is valid.
It may be a combination of upper and lower case letters. Ex ., suM. Sum. These
are not same.
Variable
A variable is used to store values. Each variable has memory location. The memory
locations are used to store the values of the variables.
Variable declaration
C++ permits declaration of variable any where inside the program. This makes the
programmer more comfortable to declare the variables.
Syntax:
The identifier v is a variable. Statement (a) declares the one variable and (b)
indicates more than one variable.
Example:
(a) int a;
Initialization
Syntax:
Ex:
int x=10;
Example Program:
#include<iostream.h>
#include<conio.h>
void main()
cout<<”x=”<<x;
cout<<”y=”<<y;
cout<<”x=”<<x;
cout<<”y=”<<y;
getch();
Output:
x=10
y=20
x=20
y=20
Dynamic initialization
Ex:
#include<iostream.h>
#include<conio.h>
void main(){
int r;
float area;
cin>>r;
cout<<”Area is “<<area;
There are,
(1) Pointers
(2) Functions
(3) Arrays
(4) References
(1) Pointers
int *x;
float *f;
#include<iostream.h>
void main(){
int x=2,*p;
p=&x;
cout<<”value of x = “<<*p;
Output:
Address of x= 4096
Value of x = 2
Variable X 4096 2
Pointer variable P
Fig.6 -Pointers
Here x is a integer variable and *p is an integer pointer. The first cout statement
displays the address of variable x. the address of x is assigned to pointer p. the variables
are always used to store address of another variable. Second statement displays the value
of x using pointer p.
Functions
A function is a self contained block of codes. It is possible to use the same name with
multiple definitions called as function overloading.
Ex :
funA() and funB() are two user defined functions. These are invoked from the body
of main. After execution of the funA(), funB() the program control returns back to the
calling function main().
#include<iostream.h>
void main()
void show();
show();
void show()
OUTPUT:
In function show()
(3) Arrays
Ex
int b[2];
#include<iostrream.h>
void mai()
int b[2]={2,4};
output:
b[0] value : 2
b[1] value : 4
(4) References
C++ reference types, declared with & operator are nearly identical but not exactly
same to pointer types. They declare alias for object variables and allow the programmer to
use variable by reference.
(2) Union
The struct is a keyword and used to combine variables of different data types into a
single record.
Syntax:
struct struct_name
struct : Keyword
struct name : An optional tag name that defines the structure type.
#include<iostream.h.
void main()
struct my_friend
char name;
int phone;
} A,B;
A.name=”Kumaran”;
A.phone=262312;
B.phone=267890; 262312
cout<<A.name; Senthil
cout<<A.phone; 267890
cout<<B.name;
cout<<B.phone;
Class
Syntax
Baseclasslist : if the class is derived class, then it follows the list of the base
class.
Member variable list : Defines the data member variables and member
functions
Example
Class circle
(2) Union
A union is same as compared to a struct, the only difference is sharing the memory
space for the variables.
Syntax:
union unionname
Example
union chartoint
int i;
};
C++ will allocate sufficient storage in union variable number to hold the big element
in the union. The union member variable number .c and .i uses the same memory location
in memory location in memory.
Ex,
int (2 bytes)
char (1 byte)
char
int
Anonymous unions
An anonymous union does not contain tag name. each element of such union can be
accessed without using tag name.
union
int k;
};
(3) Enumerated data type
The enum is a keyword. It is used for declaring enumeration data type. The
programmer can declare the new data type and define the variables of these data types that
can hold.
Example:
#include<iostream.h>
void main()
output :
true :1 false : 0
The void type is an empty data type. It can be used in two ways.
a. When specified as a function return type, void means that the function does
not return a value.
cout<<name;
b. The void keyword is also used as argument function. When found in a function
heading void means that the function does not take any arguments.
int fun(void)
{ return 1
c. when specified as a function return type and in function heading i.e, the
function neither returns a value nor require any argument.
void fun(void);
Type Modifier
The keywords signed, unsigned, short, and long are type modifiers. The type
modifiers change the meaning of the base data type to produce a new data type.
1. Each of these type modifiers is applicable for int.
Example :
Long 1;
Unsigned char c;
Signed int s;
Type casting
Definition
Type casting refers to the conversion of data from one basic type to another by
applying external use of data type.
1. Explicit
2. Implicit
( 1 ) Explicit conversion
The desired type can be achieved by typecasting a value of particular type. It is done
using type casting operator. The complier is instructed to do conversion using typecast
operator.
Example:
x=5/float(2);
float x;
x=(int) 5/2.0;
The above expression returns the value 2.5, even if an int typecast operatoris used.
The typecast operator attempts to make the expression int type, but the expression
contains float type operand. Hence it is considered as float type expression and returns the
result of float type.
#include<iostream.h>
void main()
clrscr();
cout<<int(17.78);
Output:
17
( 2 ) Implicit Type conversion
The type conversion is carried out when the expression contains different types of
data items. When the compiler carries such type conversion itself by using inbuilt datatypes
in routines then it is called imlicit type conversion.
The variable of lower data type converted into higher data type is called as
promotion.
When the variable of higher datatype converted into to lower type, is called as
demotion.
#include<iostream.h>
#include<conio.h>
void main()
int j=2.54;
int k=’A’;
char c=87.5;
cout<<”j=”<<j;
cout<<”\n k=”<<k;
cout<<”\nc=”<<c;
Output:
J=2
K=65
C=w
Constants
The constant values do not change during execution of the program. In C++ there
are two types of constants.
1. Literal
2. Symbolic
(1)Literal constant
int x= 5;
Ways Example
#include<iostream.h>
void main()
const Sunday=0;
const Monday=1;
int c=30;
cin>>c;
cout<<”\n Holiday”;
else
cout<<”\nWorking day”;
Output:
Holiday
Operators in C++
Example:
5+10
Here, 5 and 10 are constants. The symbol + is an operator that indicates the
operation to be performed and performs addition of numbers and is a single operator.
1. Arithmetic operator
2. Relational operator
3. Logical operator
4. Assignment operator
6. Conditional operator
7. Bitwise operator
8. Special operator
Arithmetic operators +, -, *, /, %
Relational operator <,>,= = , <=,>=,and !=
Assignment operator =
Special operator ,
Conditional operator ?:
Operator description
C++ operators are classified into 17 groups as shown in table. The operators with in
each category have equal precedence.
Precedenc
Operator Description Overloadable Associativity
e
1 :: scope resolution no left to right
() function call yes
2 [] array access yes left to right
-> member access yes
. no
++ -- postfix yes
dynamic_cast
static_cast
type conversion no
reinterpret_cast
const_cast
typeid Get type information no
! not logical negation yes
bitwise negation
~ compl yes
(complement)
++ -- prefix yes
+ - unary sign operations yes
* & indirection and reference yes
3 right to left
Size (of the type) of the
sizeof no
operand in bytes
new
new[] dynamic memory
yes
delete management
delete[]
(type) Cast to a given type yes
->* member pointer selector yes
4 left to right
.* member object selector no
5 * / %
arithmetic operations yes left to right
6 + -
7 << >> shift operations yes left to right
8 < <= > >=
relational operations yes left to right
9 == != not_eq
10 & bitand Bitwise AND yes left to right
11 ^ xor Bitwise XOR yes left to right
12 | bitor Bitwise OR yes left to right
13 && and logical AND yes left to right
14 || or logical OR yes left to right
Ternary conditional (if-
15 ?: no right to left
then-else)
= += -
16 = *= /= %= &= ^= |= assignment yes right to left
<<= >>=
Sequential evaluation
17 , yes left to right
operator
a. int *arr[5];
The above statement declares an array of five pointers and following operations are
invalid. Because array name and address are constant. a++ ,++a.
The above declaration declares a pointer to an array of five elements. Hence the
operations such as arr++ and ++arr are not supported.
These operators are used for referencing and dereferencing. The symbol is also used
in c++ to define reference types, and as a bitwise AND operator. We can also use the
astrick as an operator to dereference a pointer and as the multiplication operator.
Referencing operator ( & )
This operator is used for define referencing variable. A reference variable prepares
an alternative name for previously defined variable.
Syntax:
Example :
int &qt=qty;
In this example,
& reference
qt variable name
2. Once a reference variable is declared, it should not refer to any other variable. Once
the actual variable and reference variable are connected they are tied jointly
congenitally.
3. The reference variable can be created referring to pointer variable. The declaration
would be as given below:
Char *h =” C++”;
Char *&q=h;
4. A variable can contain various references. Modifying the value of one of them results
in a change in all others.
Dereferencing operator
The asterisk (*) is a variable expression used to declare a pointer to a given type. If
the operand is a pointer to function, the result is a function designations. If the operand is a
pointer to an object, the result is an lvalue, indicating that object. The following conditions,
the result of indirection is undefined.
2. The expression is the address o an automatic variable and execution and it is out of
scope.
The difference is & displays address of the variable in the RAM and * displays the
value of the variable.
The declarations of the same variable refer to different memory locations. The block
of the C++ program from where the variable can be accessed is known as the scope of the
variable.
The scope access operator :: allows a programmer to access a global name even if it
is hidden by a local re declaration of that name.
#include<iostream.h>
int a=10;
main()
Int a=20;
Output:
::a=10 a=20
malloc()
calloc()
realloc()
free()
new()
delete()
malloc()
Free()
The new operator itself calculates the size of the object without the use of
sizeof() operator.
It returns the pointer type. The programmers need not take care of its
typecasting.
The new operator allocates memory and initializes the object at once.
The new and delete operators are very easy in syntax. They can be
overloaded.
new operator
Allocates memory of specified type and returns back the starting address to the
pointer memory variable. Here element size is optional. If the new operator fails to allocate
the memory it returns null, which can be used to detect failure or success of new operator.
Syntax:
Example:
The delete operator frees the memory allocated by the new operator. This operator is
used when the memory allocated is no longer usable in the program.
Syntax:
Example
a. delete p;
#include <iostream>
#include <new>
using namespace std;
{
struct myclass
{
myclass() {cout <<"myclass constructed\n";}
~myclass() {cout <<"myclass destroyed\n";}
};
int main ()
{
myclass * pt;
pt = new myclass[3];
delete[] pt;
return 0;
}
Output:
myclass constructed
myclass constructed
myclass constructed
myclass destroyed
myclass destroyed
myclass destroyed
Comments
Example
Comma operator
2. The statements followed by declaration statements like clrscr(), cin, cout can be
terminated by comma operator.
Ex.
#include<iostream.h>
#include<conio.h>
void main()
clrscr(),
Most of the control structures that we will see in this section require a generic
statement as part of its syntax. A statement can be either a simple statement (a simple
instruction ending with a semicolon) or a compound statement (several instructions grouped
in a block), like the one just described. In the case that we want the statement to be a
simple statement, we do not need to enclose it in braces ({}). But in the case that we want
the statement to be a compound statement it must be enclosed between braces ({}),
forming a block.
if statement
Syntax:
if (condition) statement;
Where condition is the expression that is being evaluated. If this condition is true,
statement is executed. If it is false, statement is ignored (not executed) and the program
continues right after this conditional structure.
For example, the following code fragment prints x is 100 only if the value stored in
the x variable is indeed 100:
if (x == 100)
if we want more than a single statement to be executed in case that the condition is
true we can specify a block using braces { }
if (x == 100)
cout << x;
if else statement
We can additionally specify what we want to happen if the condition is not fulfilled by
using the keyword else. Its form used in conjunction with if is:
Syntax:
if (condition)
statement1;
else
statement2;
For example:
if (x == 100)
cout << "x is 100";
else
Prints on the screen x is 100 if indeed x has a value of 100, but if it has not -and
only if not- it prints out x is not 100.
The if + else structures can be concatenated with the intention of verifying a range
of values. The following example shows its use telling if the value currently stored in x is
positive, negative or none of them (i.e. zero):
if (x > 0)
cout << "x is positive";
else if (x < 0)
cout << "x is negative";
else
Remember that in case that we want more than a single statement to be executed,
we must group them in a block by enclosing them in braces { }.
else if Ladder
When a series of many conditions have to be checked we may use the ladder else if
statement which takes the following general form.
if(condition1)
statement 1;
elseif(condition2)
statement2;
elseif (condition3)
statement3;
else if (condition)
statement n;
else default
statement;
statement-x;
This construct is known as if else construct or ladder. The conditions are evaluated
from the top of the ladder to downwards. As soon on the true condition is found, the
statement associated with it is executed and the control is transferred to the statement – x
(skipping the rest of the ladder. When all the condition becomes false, the final else
containing the default statement will be executed.
#include <iostream>
using namespace std;
int main()
{
int x;
for(x=0; x<6; x++)
{
if(x==1) cout << "x is one\n";
else if(x==2) cout << "x is two\n";
else if(x==3) cout << "x is three\n";
else if(x==4) cout << "x is four\n";
else cout << "x is not between 1 and 4\n";
}
return 0;
}
Output:
The if-else statement allows a choice to be made between two possible alternatives.
Sometimes a choice must be made between more than two possibilities. For example the
sign function in mathematics returns -1 if the argument is less than zero, returns +1 if the
argument is greater than zero and returns zero if the argument is zero. The following C++
statement implements this function:
if (x < 0)
sign = -1;
else
if (x == 0)
sign = 0;
else
sign = 1;
This is an if-else statement in which the statement following the else is itself an if-
else statement. If x is less than zero then sign is set to -1, however if it is not less than zero
the statement following the else is executed. In that case if x is equal to zero then sign is
set to zero and otherwise it is set to 1.
Novice programmers often use a sequence of if statements rather than use a nested if-else
statement. That is they write the above in the logically equivalent form:
if (x < 0)
sign = -1;
if (x == 0)
sign = 0;
if (x > 0)
sign = 1;
LOOPS IN C++
Loops are basically means to do a task multiple times, without actually coding all
statements over and over again. Loops are used to repeat a block of code. Being able to
have your program repeatedly execute a block of code is one of the most basic but useful
tasks in programming -- many programs or websites that produce extremely complex
output (such as a message board) are really only executing a single task many times. (They
may be executing a small number of tasks, but in principle, to produce a list of messages
only requires repeating the operation of reading in some data and displaying it.) Now, think
about what this means: a loop lets you write a very simple statement to produce a
significantly greater result simply by repetition.
1. for loop
2. while loop
3. do while loop
for Loop
The for loop allows execution of a set of instructions until a condition is met.
Condition may be predefined or open-ended. Although all programming languages provided
by c/c++ is worth mentioning.
Syntax:
Statement block;
#include<iostream.h>
void main()
for(int i=0;i<=5;i++)
cout<<i<<”\n”;
Output:
4
5
while loop
Syntax
while(condition)
The condition may be expression. The loop statements will be executed till the
condition is true.
#include<iostream.h>
void main()
int i=0;
while(i<=5)
cout<<i<<”\n”;
i++;
getch();
Output:
do-while loop
Syntax:
do
{
Body of the loop;
}while(condition);
#include<iostream.h>
void main()
int i=0;
cout<<i<<”\n”;
i++;
} while(i<=5);
getch();
Output:
FUNCTIONS IN C++
The Process of dividing a large program in to tiny sub program is called modular
programming.
Advantages of functions:
Parts of function
Definition of a function
Function call
Actual arguments
Formal arguments
Return statement
Function prototype
A prototype statement helps the compiler to check the return and argument types of
the function. It contains return type, function name and argument list.
Example:
a. void show(void);
Explanation
a. In example (a) the return type is void. The function won’t return any value.
c. In example (c) the return type is float and int with arguments.
Function definition
The first line of the function is called function declarator and is followed by function
body. The block of statements followed by function declarator is followed by function
declarator is called function definition.
Function call
The arguments declared in calling function are called actual arguments. The
arguments declared in called function are called formal arguments.
void main()
return(j+k);}
Example:
#include<iostream.h>
#include<conio.h>
void main()
float x,y=2.4;
int z=5;
x=sum(y,z);
return (j+k);
Output:
x value is 7.4
void main()
float x, y=2.4;
Actual arguments
int z=5;
}
Function Body
Inline functions
When a function is declared as inline function, the compiler copies the function body
is inserted in place of function call during compilation. It increases the speed of the
execution. Repetitive function calls and returning values are removed.
Syntax:
inline function_name
Example:
return (k*k);
Following are some situations where inline function may not work:
#include<iostream.h>
#include<conio.h>
return (j*j);
void main()
clrscr();
int p=3,q=3,r,s;
r=SQUARE(++p);
s=square(++q);
cout<<”r=”<<r<<”\n s=”<<s;
Output:
r=25
s=16
Function overloading
Defining multiple functions with same name is known as function overloading. The
overloaded function must be different in its argument list and with different data types.
Example:
#include<iostream.h>
#include<conio.h>
int sqr(int);
float sqr(float);
main()
int a=15;
float b=2.5;
cout<<”square of a =”<<sqr(a)<<”\n”;
cout<<”square of b=”<<sqr(b)<<”\n”;
return 0;
int sqr(int s)
return (s*s);
float sqr(float j)
return (j*j);
Output:
Square of a = 225
Square of b = 6.25
UNIT III
Object
The selected program objects must be similar to real time objects. Objects occupy
space in memory. Every object has its own properties.
Class
STRUCTURES IN C++
Syntax:
struct structure_name
variable1;
variable2;
};
In this syntax,
struct Keyword.
Example:
struct item
int codeno;
float prize;
int qty;
};
The operators (.) and () arrow are used to access the member variables of struct.
The (.) operator is used for simple object and () is used for pointer variable.
Example:
a.codeno
a.price
a.qty
bcodeno
bprice
bqty
CLASSES IN C++
Syntax:
private:
declaration of variable;
public:
declaration of variable;
};
Example:
class item
private:
int codeno;
float prize;
int qty;
void values();
public:
void show();
};
The class is enclosed by curly braces and terminated by a semi colon. The member
function is divided in two sections, i.e. private and public. These are terminated by (:).
functions are declared in private section and data members are declared in public section.
DECLARING OBJECTS:
It is individual
Example:
Item a,b,*c;
Item is a class name. a,b are the simple objects and *c is pointer to class.
The object can access the public member variable and functions of a class by using
operator dot(.) and arrow ().
Syntax:
a is an object
The keyword public can be used to allow object to access the member variables of
class directly like structure. It is terminated by colon (:). the member variables and
declared followed by the public can be accessed directly by the object.
The private keyword is used to prevent direct access to member variables or function
by the object. The class by default produces this effect. The structure variables are
functions of struct from access the private keyword is used.
The protected keyword is same like private. It was used in inheritance of class.
Example:
#include<iostream.h>
#include<conio.h>
struct item
int codeno;
float price;
int qty;
void show()
codeno=125;
price=195;
qty=200;
cout<<” Codeno=”<<codeno;
cout<<”\nprice =”<<price;
cout<<”\n quantity=”<<qty;
};
int main()
clrscr();
return 0;
Output:
Codeno=125
Price=195
Qty=200
The member function must be declared inside the class. They can be defined public
or private or inside or outside the class. The member function inside the class are treated as
inline function is small then it should be defined inside the class.
A member function of a class can invoke any other member function of its own class.
This called as nesting of member functions. This can be terminated by semi colon.
#include<iostream.h>
class A
private:
int v1=20;
public:
int v2=30;
void show()
};
void main()
A a1;
a1.show();
Output:
The function inside the class is considered as inline function. To define a function outside
the class following care must be takes,
The function name must be preceded by class name and its return type
separated by scope access operator.
Static is a keyword and its value is initialized as zero in default. A static function is
only recognized inside the scope of the present class.
Syntax:
Example:
static int c;
When function is defined as static it can be access only member variables and
functions. The static keyword makes the function free from the individual object of the class
and its scope is global in the class without creating any side effect from other part of the
program.
The following points while declaring static function:
1. Just one copy of static member is created in the memory for entire class. All
objects of the class share the same copy of static member.
2. Static member functions can access only static data members or functions.
5. When one of the objects changes the value of data member variables, the
effect is visible to all the objects of the class.
#include<iostream.h>
#include<conio.h>
class test
{
int code;
static int count;
public :
void setcode(void)
{
code= ++count;
}
void showcode(void)
{
cout<<"object number"<<code<<endl;
}
static void showcount(void)
{
cout<<"count"<<count<<endl;
}
};
int test::count;
int main()
{
clrscr();
test t1,t2;
t1.setcode();
t2.setcode();
test::showcount();
test t3;
t3.setcode();
test::showcount();
t1.showcode();
t2.showcode();
t3.showcode();
getch();
return(1);
}
Output:
Count 2
Count 3
Object number 1
Object number 2
Object number 3
#include<iostream.h>
class IDGenerator
private:
public:
};
int IDGenerator::s_nNextID = 1;
int main()
cout << "The next ID is: " << IDGenerator::GetNextID() << endl;
return 0;
Output:
It can be initialized in main() like other variable. The static member variable using
class name and scope access operator can be accessed.
#include<iostream.h>
int c=11;
class bita
{
public:
static int c;
};
void main()
clrscr();
int c=3;
Output:
Class member c= 22
ARRAY OF OBJECTS
Array is a collection of similar datatypes. Array can be of any data type including
user defined data type, created by using struct, class and typedef declarations. We can also
create an array of objects.
#include<iostream.h>
#include<conio.h>
class player
private:
char name[20];
int age;
public:
void input()
cin>>name;
cout<<”Age :”;
cin>>age;
}
void display(void)
};
int main()
player cricket[3];
cricket[i].input();
cricket[j].display();
return 0;
Output:
Age : 14
Age : 15
Age : 14
Age : 14
Age : 15
Age : 14
friend FUNCTIONS
class ac
private:
char name[15];
public:
void read()
cin>>name;
};
void showbal(ac a)
cout<<”\n name”<<a.name;
int main()
ac k;
k.read();
showbal(k);
return 0;
Output:
Name : saranya
Member functions are also overloaded in the same fashion as other ordinary
functions. Overloading is nothing but one function is defined with multiple definitions with
same function name in the same scope.
#include<iostream.h>
class abc
{
public:
int num(int);
double num(double);
};
int abc::num(int x)
int ans;
ans=abs(x);
return(ans);
double abc::num(double d)
double ans;
ans=fabs(d);
return(ans);
int main()
clrscr();
abc n;
return 0;
Output:
The constructors construct the object and destructor destroys the object. There are
opposite to each other. The compiler automatically executes this function.
The C++ run time arrangement takes care of this execution. When a object is
created constructor is executed. The programmer can also pass these values to the
constructor to initialize member variables with different values.
The destructor destroys the object. the only difference is that destructor is preceded
by ~ operator.
Syntax for Constructor
class_name()
B()
~class_name()
~B()
CONSTRUCTOR
CONSTRUCTOR
1. Destructor has the same name as that of the class it belongs to and preceded by ~
(tilde) symbol.
2. Like constructor the destructor does not have return type and not even void.
3. Constructor and destructor cannot be inherited, though a derived class can call the
constructors and destructors of the base class.
5. Only one destructor can be defined in the destructor. The destructor does not have
any argument.
8. Constructor and destructor can make implicit calls to operators new and delete if
memory allocation/ de allocation is needed for an object.
The initialization of member variables of class is carried out using consttructors. The
constructor also allocates required memory of the object.
Example
#include<iostream.h>
#include<conio.h>
class num
private:
int a,b,c;
public:
cout<<”Constructor is called”;
a=0;b=0;c=0;
main()
num x;
Output:
Constructor is called.
The above example class num has three member integer variables a, b and c, the
declaration of constructor can be done inside the class and definition outside the class. In
definition, the member variables of a class num are initialized to zero.
It is also possible to create constructors with arguments and such constructors are
called as paramaterized constructors. For such constructors it is necessary to pass values to
the constructor when object is created.
Example
#include<iostream.h>
#include<conio.h>
class num
private:
int a,b,c;
public:
cout<<”Constructor 1 is called”;
num::num(int m)
cout<<”Constructor 2 is called”;
main()
num x;
num x(5);
Output:
Constructor 1 is called
Constructor 2 is called
Overloading Constructor
Like functions, it is possible to overload constructors. A class contains more than one
constructor. This is known as constructor overloading. Depending upon the arguments, the
complier executes appropriate constructor.
When the object is created, the constructor with three arguments is called because
the declaration of an object is followed by three arguments. For object y, constructor with
two arguments is called and lastly object z, which is without any argument, is candidate for
constructor without argument.
COPY CONSTRUCTOR
Using copy constructor, it is possible for the programmers to declare and initialize
one object using reference of a another object. This constructor is called as copy
constructor.
Example
n=j.n;
#include<iostream.h>
#include<conio.h>
class num
int n;
public:
n=k;
n=j.n;
void show(void)
cout<<n;
};
main()
clrscr();
num j(50);
num k(50);
numk(j);
num l=j;
num m;
m=j;
j.show();
k.show();
l.show();
m.show();
return 0;
Output:
DESTRUCTOR
Destructor is also a member function like constructor. It destroys the class objects
created by constructors. The destructors have the same name as their class, preceeded by a
tilde~.
#include<iostream.h>
struct text
text() //constructor
~text() //destructor
};
void main()
clrscr();
Output:
Constructor is executed.
Destructor is executed.
ANONYMOUS OBJECTS
Objects are created with names. It is possible to create objects without name and
such objects are known as anonymous objects. When constructor and destructors are
invoked, the data members of the class are initialized and destroyed respectively. Thus
without object we can initialize and destroy the contents of the class.
UNIT IV
OPERATOR OVERLOADING
The capability to relate the existing operator with a member function and use the
resulting operator with objects of its class as its operands is called operator overloading.
Syntax:
Statement 1;
Statement2;
Example
Number T;
T.x=x+D.x;
T.y=y+D.y;
return T;
Overloaded operators are redefined within a C++ calss using the keyword operator
followed by an operator symbol. When the operator is overloaded, the produced symbol is
called the operator function name. a friend class requires one argument for unary operators
and two for binary operators.
num operator+(num);
(b) The public declaration section of the class should contain the prototype of he
function operator().
(c) Define the definition of the operator function with proper operations for which
it is declared.
OVERLOADING UNARY OPERATORS
The operator ++,-- and – are unary operators. The unary operators ++ and –- can
be used as prefix or suffix with the functions. These operators have single operand.
#include<iostream.h>
#include<conio.h>
class num
private:
int a,b,c,d;
public:
a=j;
b=k;
c=m;
d=l;
void show(void);
};
void num::show()
{cout<<”a=”<<a<<”b=”<<b<<”c=”<<c<<”d=”<<d;
main()
clrscr();
num x(3,2,5,7);
x.show();
++x;
x.show();
return 0;
Output:
It require one argument. It contains value of a object. two objects o1,o2, the
overload function can be declared as follows,
Num class
O2 object
O3=o1+o2;
O3=o1+o2;
O3=operator + (o1,o2);
X=y+3; or X=3+y;
The difference between member function and friend function is that the member
function takes arguments explicitly.
Syntax:
statement1’
#include<iostream.h>
class complex
float real,image;
public:
complex()
real=image=0;
real=r;
image=i;
c.real=-c.real;
c.imag=-c.imag;
void display()
cout<<”\nimage :”<<imag;
};
void main()
clrscr();
c1.display();
c2=-c1;
c2.display();
Output:
Real : 1.5
Image : 2.5
After Negation
Real : -1.5
Image : -2.5
TYPE CONVERSION
#include<iostream.h>
class data
int x;
float y;
public:
data()
x=0;
f=0;
data (float m)
x=2;
f=m;
void show()
cout<<”\n x= “<<x<<”f=”<<f;
};
int main()
clrscr();
data z;
z=1;
z.show();
z=2.5;
z.show();
return 0;
Output:
X=2 f=1
X=2 f=1
X=2 f=2.5
X=2 f=2.5
The complier does not have any knowledge about the user- defined data type built
using classes. In this type of conversion, the programmer explicitly needs to tell the
complier how to perform conversion from class to basic type.
#include<iostream.h>
class data
int x;
float y;
public:
data()
x=0;
f=0;
Operator int()
return(x);
Operator float()
return f;
{
x=2;
f=m;
void show()
cout<<”\n x= “<<x<<”f=”<<f;
};
int main()
clrscr();
int j;
float f;
data a;
a=5.5;
j=a;
f=a;
cout<<”Value of J= “<<j;
cout<<”Value of F=”<<f;
return 0;
Output:
Value of j=2
Value of f=5.5
There are two ways to convert object data type from one class to another. One is to
define a conversion operator function in source class or a one argument constructor in a
destination class.
Example:
X=A;
Here X is an object of class XYZ and A is an object of class ABC. The class ABC data
type is converted to class XYZ. The conversion happens from class ABC to XYZ. The ABC is a
source class and XYZ is a destination class.
TYPES OF INHERITANCE
Single inheritance
When only one base class is used for derivation of a class and the derived class is
not used as base class.
Here A is a base class. B is a derived class. This type involves one base and derived
class. Further, no class is derived from B.
#include<iostream.h>
#include<conio.h>
class A
public:
int v1=10;
class B
void show()
};
void main()
B obj1;
obj1.show();
Output:
Multiple inheritance
When two or more base classes are used for derivation of a class.
A B
A and B are the base classes. C is a derived class. Class C inherits the properties of
both A and B. Further, Z is not used as a base class.
#include<iostream.h>
#include<conio.h>
class a
public:
int a=10;
};
class b
public:
int b=20;
show()
cout<<”a=”<<a<<”\n b=”<<b;
};
main()
c obj1;
obj1.show();
Output:
A= 10
B=20
Hierarchal inheritance
When a single base class is used for derived of two or more classes.
B C D
A is only one base class. A,B and C are derived classes. Further, B,c and D are not
used for deriving a class.
#include<iostream.h>
#include<conio.h>
class A
public:
int a=10,b=20,c=20;
};
class B::public A
public:
void showa()
cout<<”A=”<<a;
};
public:
void showb()
cout<<”B=”<<b;
};
public:
void showc()
cout<<”C=”<<c;
};
void main()
B obj1;
obj1.showa();
C obj2;
obj2.showb();
D obj3;
obj3.showc();
getch();
Output:
A=10
B=20
C=30
Multilevel inheritance
When a class is derived from another derived class. Derived class is act as a base
class for another class.
#include<iostream.h>
#include<conio.h>
class A
{
public:
int a;
};
class B :: public A
public:
void get()
cin>>a;
};
class C :: public B
public:
void show()
cout<<”A=”<<a;
};
void main()
C obj1;
obj1.get();
obj1.show();
getch();
OUTPUT:
A=4
Hybrid inheritance
B C
Fig.11-Hybrid inheritance
Here A,B are the single inheritance. B,C and D are the multiple inheritance.
#include<iostream.h>
#include<conio.h>
class A
public:
int a;
};
class B :: public A
public:
void geta()
cout<<”Enter A”;
cin>>a;
};
class C
public:
int b;
void getb()
cout<<”Enter B”;
cin>>b;
};
class D :: public B,C
public:
void show()
cout<<”A=”<<a<<”\nB=”<<b;
};
void main()
D obj1;
obj1.geta();
obj1.getb();
obj1.show();
getch();
Output:
Enter A 10
Enter B 20
A= 10
B=20
Multipath inheritance
#include<iostream.h>
#include<conio.h>
class A
public:
int a,b;
};
class B: public A
public:
void geta()
cout<<”Enter A value “;
cin>>a;
};
class C : public A
public:
void getb()
cout<<”Enter b value”;
};
public:
void show()
coout<<”A=”<<a<<”\nB=”<<b;
};
{ Enter a value: 10
obj1.geta(); A=10
obj1.getb(); B=30
obj1.show();
Class a1
protected :
int a;
};
protected:
int b;
};
Abstract classes
When a class is not used for creating objects it is called as abstract class. It act as a
base class only.
UNIT V
POINTER
A pointer is a memory variable that stores a memory address. Pointers can have any
name that is legal for other variables and it is declared in the same fashion like other
variables but it is always denoted by * operator.
POINTER DECLARATION
int *x;
float *y;
char *f;
In the first statement x is an integer pointer that holds the integer variable address.
#include<iostream.h>
#include<conio.h>
main()
int n;
clrscr();
cin>>n;
cout<<”Value of n =”<<n;
cout<<”Address of n= “ <<(unsigned)&n;
getch();
OUTPUT:
value of n=10
Address of n = 4068
POINTER TO CLASS
We can also define pointer to class. Here , starting address of the member variables
can be accessed. Such pointers are called class pointer.
Example ;
Class book
{
char name[25];
int pages;
};
Ptrname ptrpages;
POINTER TO OBJECT
Like variables, objects also have an address. A pointer can point to specified object.
Bill s;
Bill *ptr=&s;
Ptr getdata(45,1.2,12);
(*ptr).show();
The keyword this is a local variable that is always present in the body of any non
static member function. It does not need to be declared.
Example
#include<iostream.h>
#include<conio.h>
class num
int num;
public:
void input()
cin>>num;
void show()
number min(num t)
if (t.num<num)
return t;
else
return *this;
};
void main()
number n,n1,n2;
n1.input();
n2.input();
n=n1.min(n2);
n.show();
Output:
It is possible to declare a pointer which points to the base class as well as the
derived class. One pointer can point to different classes. For example, X is a base class and
Y is a derived class. The pointer points to X can also point to Y.
#include<conio.h> {
class A clrscr();
{ B *cp;
public: B b;
int b; cp=&b;
{ cpd=350;
} }; cpdisplay();
{ }
public:
int d; Output:
{ b=100 d=350
cout<<”b=”<<b<<
cout<<”\n”<<”d=”<<d;
In this program cp points to the objects of derived class. The pointer cp is pointer to
class B. the variable b is an object of class B. the address of b is assigned to the pointer cp.
The pointer cp can access the member variables of both base and derived classes.
ARRAYS
Array is a collection of elements of similar data types in which each element is unique
and located in separate memory locations.
Declaration
int a[5];
it tells to the compiler that ‘a’ is an integer type of array and it must store five
integers. The compiler reserves two bytes of memory for each integer array element. In the
same way array of different data types are declared as below:
char ch[10];
float real[10];
long num[5];
Array initialization
Here, five elements are stored in an array ‘a’. The array elements are stored
sequentially in separate locations. Reading of array elements begins from zero. Array
elements are called with array name followed by element numbers.
CHARACTERISTICS OF ARRAY
1. The declaration int a[5] is nothing but creation of five variables of integer type in
memory. Instead of declaring five variables for five values, the programmer can
define them in an array.
2. All the elements of an array share the same name, and they are distinguished
from one another with the help of element number.
3. The element number in an array plays a major role in calling each element.
int a[5]={1,2,3,4,5};;
if the programmer needs to replace 5 with 10, he/she is not require to change all
other numbers except 5. To carry out this task the statement a[4]=10 can be
used. Here other three elements are not disturbed.
Example :
B=a[2];
a[2]=a[3];
6. The array elements are stored in continuous memory locations. The amount of
storage require for holding elements of the array depends upon its type size. The
total size in bytes for a single dimensional array is computed as shown below;
Before compiling and linking the source code, we need to specify the appropriate
memory model. Using memory models, we can set the size limits of the data and code.
Tiny
Small
All code should fit in a single 64 KB segment and all data should fit in a 64 KB
segment.
Medium
All pointers to data are 16 bits, but all jumps and calls require 32 bits addresses.
Access data is fast but slower program execution.
Dynamic binding of member functions in c++ can be done using the keyword virtual.
The member function followed by the virtual keyword is called virtual function.
int d;
public:
};
int k;
public:
In this example, base and derived classes have the same member function display ()
preceded by the keyword virtual. The various forms of virtual function in base and derived
classes are dynamic bounded. The references are detected from the base class.
VIRTUAL FUNCTION
Virtual function of base classes must be redefined in the derived classes. The
programmer can use the same function name in any derived class, even if the number and
type of arguments are matching. The function overrides the base class function of the same
name. virtual functions can only be member functions. We can also declare the functions as
given below:
int base :: get(int) and int derived :: get(int) even when they are not virtual.
In virtual function if two functions with the same name have different arguments,
C++ complier them as different, and the virtual mechanism is dropped.
#include<iostream.h>
#include<conio.h>
class first
{
int b;
public:
first() { b=10};
cout<<”\n b=”<<b;
}};
int d;
public:
second(){ d=20;}
void display()
cout<<”\n d= ”<<d;
};
int main()
clrscr();
first f,*p;
second s;
p=&f;
pdisplay();
p=&s;
pdisplay();
return 0;
Output :
b=10
d=20
APPLICATIONS WITH FILES
FILE:
The file is an accumulation of data stored on the disk created by the user. The
programmer assigns file name. The file name are unique and are used to identify the file.
No two files can have the same name In the same directory. There are various types of files
such as text files, program files, data files, execution files etc.
Data files contain a combination of numbers, alphabets, symbols etc. called data.
Data communication can be performed between program and output devices or files
and program. File streams are used to carry the communication among all devices. The
stream is nothing but flow of data in bytes in sequence. If data were received from
input devices in sequence then it is called as source stream. When the data were received
from input devices then it is called as destination stream.
Stream is nothing but flow of data. In object programming the streams are
controlled using the classes. The operations with the files are mainly two types. There are,
read and write.
ios is a base class. All other classes are derived from the ios class. These classes
contain several member functions that perform input and output operations. The streambuf
class has low level routines for controlling data buffer.
The streambuf and ostream classes control input and output functions respectively.
The ios is the base class of these two classes. The member function of these classes handle
formatted and unformatted operations. The functions get(), getline(), read() and overloaded
extraction operatord(>>) are defined in the istream class. The function put(), write() and
overloaded insertion operation operators (<<) are defined in the ostream class.
The iostream class is also a derived class. It is derived from istream and ostream
classes. There are also a derived classes. It is derived from istream and ostream classes.
There are also another three useful derived classes. They are istream_withassign,
ostream_withassign and ostream_withassign. They are derived from istream,otream, and
fstream classes.
The fileBuf accomplishes input and output operations with files. The streambuf class
does not organize streams for iput or output operations. The derived classes of streambuf
perform these operations. It also arranges a space for keeping input data and for sending
output. The I/O functions of classes istream and ostream invoke the filebuf functions to
perform the insertion or extraction on the streams.
The FSTREAMBASE acts as a base class for fstream, ifstream and ostream. The
functions such as open() and close() are defined in fstreambase.
The OFSTREAM class derived from fstreambase and ostream classes. It can access
the member functions such as put(), seekg(), write() and tellp(). It allows output operations
and provides member function open() with output mode.
The FSTREAM allows simultaneous input and output operations on a filebuf. The
member functions of base classes istream and ostream start the input and output.
C++ allows file manipulation command to access file sequentially or randomly. The
data of sequential file must be accessed sequentially i.e, oe character at a time. In order to
access nth number of bytes, all previous characters are read and ignored. There are number
of functions to perform read and write operations with files. Some function read/write single
character and some function read/write block of binary data. The put() and get() functions
are used to read or write a single character whereas write() and read() are used to read or
write block of binary data.
The function get() is a member function of the class fstream. This function reads a
single character from the file pointed by the get pointer.
The put() function writes a character to the specified file by the stream object. it is
also a member of fstream class. The put() function places a character in the file indicated by
put pointer.
#include<iostream.h> While(1[text]!=’\o’)
#include<conio.h> Io.put(text[1++]);
#include<string.h> Io.seekg(0);
cin.getline(text,50); cout<<c;
int i=0; }
In this program file data is opened in read and write mode. The getline() function
used to read the string and it stores in the array text[50]. The statement io.put(text[i++])
reads ted data and writes in the screen.
The insertion and extraction operators known as stream operator handles formatted
data. The programmer needs to format data in order to represent it in a suitable fashion.
ASCII codes are used by the I/O devices to share or pass data to share or pass to the
computer system. But central processing unit manipulates the data using binary numbers 0
and 1. for this reason, it is essential to convert the data while accepting data from input
devices and displaying the data on output devices.
cout<<k; //displaying value of k on screen
here, k is an integer variable. The operator << converts value of integer variable k
into stream of ASCII character. In the same fashion, the << operator converts the ASCII
characters entered by the user to binary. The data is entered through the keyboard,
standard input devices. For example, we entered 2 the stream operator >> gets ASCII
codes of the individual digits of the entered number 2. The stream operator << converts the
value of k that is stored in binary format into equivalent ASCII codes.
#include<fstream.h>
#include<constream.h>
int main()
clrscr();
char c;
ifstream in(“dat”);
if(!in)
return 1;
while(in.eof()==0)
cout<<(char)in.get();
return 0;
In this program the data file is opened in read mode. The file already exists. Using
get() member of ifstream class, the contents of file is read an displayed.
The data entered by the user are represented in ASCII format. However, the
computer can understand only machine formats 0 and 1. when data is stored in text format
numbers are stored as characters and occupy more memory space. The limitations can be
overcome using write() and read() functions. The write() and read() functions. The write()
and read() functions use binary format of data during operations. The data representation is
same in file and system. The bytes required to store an integer in text form depends upon
its size where as in binary format the size is fixed. The binary form is exact and allows quick
read and write operation because no conversion takes place during operations. The formats
of the write() and read() functions are given below:
The functions read() and write() perform write and read() operations in binary
format that is exactly same as internal representation of data in the computer. Due to
these capabilities of the functions, large data can be stored in small amount of memory.
Both these functions are also used to write and read operation only data members are
written to the file and the member functions are ignored.
Data files always contain large information and the information always changes. The
changed information should be updated otherwise the data files are not useful. Thus to
update data in the file we need to update the data files with latest information. To update
the data files with latest information. To update a particular record of data file it may be
stored anywhere in the file it is necessary to obtain at which location the data object is
stored.
The sizeof() operator determines the size of object. consider the following
statements.
int size=sizeof(o);
where o is an object and size is an integer variable. The sizeof() operator returns the
size of object o in bytes and it is stored in the variable size. Here, one object is equal to one
record.
The position of nth record or object can be obtained using the following statements.
Here p is the exact byte number of the number of the object that is to be updated, n
is the number of object, and size is the size in bytes of an individual object.
P=(5-1*26) i.e, p=104 thus the fifth object is stored in a series of bytes from 105 to
130.
TEMPLATES
A function that works for all c++ data types is called as templates. Templates help
the programmers to declare group of functions or classes.
Need of template
Template is a technique that allows using a single function that can process any
type of data types. Using template we can create a single function that can process any
type of data. The formal arguments of template functions are of template type. They can
accept data of any such as int, float, long etc. thus, a single function can be used to accept
values of different datatypes.
Template declaration
The first statement template class<T> tells the complier that the following class
declaration can use the template data type. T is a variable of template type that can be
used in the class to define variable of template type. Both template and class are keywords.
The <> is used to declare variables of template type that can be used inside the class to
define variables of template type. One or more variables can be declared separated by
comma. Templates cannot be declared inside class or functions. They must global and
should not be local.
T K;
Where k is the type of type template. Most of the authors use T for defining template
instead of T, we can use any alphabet.
#include<iostream.h>
#include<conio.h>
class data
public:
data (T c)
}};
int main()
clrscr();
return 0;
output :
Template class<T>
Function_name()
//code
Example:
void show (T X)
cout<<”\n x=”<<x;
show(c);
show(i);
show(d);
Like functions classes can be declared to handle different data types. The class
contains more than one argument. The arguments are separated by comma with template
declaration. The declaration is as follows:
class name_of_class
Example:
#include<iostream.h>
#include<conio.h>
class data
public:
data(T1 a, T2 b)
{
cout<<a<<b;
}};
void main()
clrscr();
getch();
Output :
2 2.5
15 c
In this program, the constructor has two parameters of template type. Consider
data<int, float> h(2,2.5). the compiler tells that first argument is of integer type and
second argument is of float type.
Syntax:
statements;
#include<iostream.h>
#include<conio.h>
void show( A c, B I, C f)
cout<<”\n c=”<<c<<”i=”<<i<<”f=”<<f;
int main()
clrscr();
show(‘A’,8,50.25);
show(7,’B’,70.89);
return 0;
Output:
Exception handling
The errors may be logical errors or syntactic error. The logical errors remain in the
program due to poor understanding of the program. The syntax mistakes are due to lack of
understanding of programming language. C++ provides exception handling procedure due
to reduce the errors that a programmer makes.
There are,
1. Synchronous exceptions
2. Asynchronous exceptions
C++ has a well organized object oriented method to control run time errors that
occur in the program. The goal of exception handling is to create a routine that detects and
sends an exceptional condition in order to execute suitable action
try
statement 1;
statement 2;
throw (excep);
throw excep;
throw;
try
{
statement 1;
statement 2;
catch (argument)
try block
throw block
Throws exception
Catch block
C++ exception handling mechanism provides three keywords: try, throw and catch.
the keyword try used at the starting of exception. The throw block is present inside the try
block. Immediately after try block, catch () block is present.
As soon as exception is found, the throw statement inside the try block throws an exception
for catch() block that an error has occurred in the try block throws an exception occurring
inside the try block are used to throw exception. the catch receives the exceptin send by the
throw block.
Statement 1;
Statement 2;
Statement;
Statement;
Statement;
Statement;
Statement;
A string is nothing but sequence of characters. The string can contain small and
capital letters, numbers and symbols. String is an array of character type. Each element of
string occupies a byte in the memory. Every string is terminated by a null character.
Functions Description
#include<iostream.h>
#include<conio.h>
#include<string.h>
int main()
char name[15];
clrscr();
cin>>name;
return 0;
}
Output:
Length of string is : 7