Sie sind auf Seite 1von 48

OOPs With C++

UNIT-I
Programming paradigms:
Programming paradigms means the way of writing a program depending upon the requirements.
These requirements mainly focus the task of development team to develop programs for the smallscale projects to the large-scale projects. The programming paradigms is categorized into the
following way
2. Procedural programming
3. Structural programming
4. Object oriented programming
Procedural programming:
In the procedural programming approach the problem is divided into sequence of functions. The
primary focus in this approach is on functions. Number of functions are written to accomplish the task
of a project. In a multifunction program important data items are placed as global data and they may
be accessed by all the functions. Each function is also having a set of local data items.

Global data

F1
Local
data
data

F2

F3

Local
data

Local
data

F4
Local
data

The following are the important features:


1.
2.
3.
4.
5.

Programs are organized in the form of subroutines and all data items are global
Program control achieved by call to subroutines
Code reusability occurs
Suitable for medium sized software application
Difficult to maintain and enhance the program code

The drawback is there is no data security for global data.


Advantages of procedural programming include its relative simplicity, and ease of implementation of
compilers and interpreters.
Examples of procedural programming languages include FORTRAN, ALGOL, Pascal, C, MODULA2,
Ada, BASIC.
Structured programming
Structured programming is used to develop large-scale projects. The large-scale project consists of
large development team, developing different parts of the same project independently. The separately
compiled program modules are grouped together to create big projects. In this multiple module
program, each module is having a separate set of related functions. The following are important
features of structured programming

Global data

M1

Module 2
F1
F2

M3

1.
2.
3.
4.
5.
6.

Importance given to algorithm rather than data


Projects can be broken up into modules and programmed independently
Each module is divided into individual procedures that perform separate tasks.
Module are independent of each other as far as possible
Modules have their own local data and processing logic
User defined data types are introduced.

Object oriented programming: OOP is a method of implementation in which programs are


organized as co-operative collections of objects, each of which represents an instance of some class
and whose classes are all members of a hierarchy of classes united through the property called
inheritance.
Object A
Object B

Data

Function

Data

Communication

Function

Function

Data

Object based language


Object oriented language

= encapsulation + object identity


= object based + inheritance + polymorphism

Object oriented programming is an extension for the basic structured programming


language. In this technique more importance is given to the data. Using this technique we can
combine data as well as operations that can be performed on data as a single unit using
Class data type.
Benefits of OOP
1.
2.
3.
4.
5.

Implementing Reusability by making Reusable Classes and creating Objects from those
Classes.
Providing various levels of Data protection and hiding by using Public, Private and Protected
access specifiers.
Providing Protection to Data and Functions both.
Helps in creating Flexible, Extensible and Maintainable code.
Effective solutions for Real World problems by implementing Classes representing Real World
Entities.

6.

Quick software development due to Reusability and easy implementation of Real World Entities
and their Relationships using Inheritance.

The following are the important features of object-oriented programming.

Importance given to data rather than algorithm


Data abstraction is introduced in addition to procedural abstraction.
Data and associated operations are unified into a single unit
The objects are grouped with common attribute operation and semantics.
Programs are designed around the data being operated rather than operate themselves.
Relation ships can be created between similar, yet distinct data types.

Difference between Procedural Programming and Object Oriented Programming


No Procedural Programming
1
It is a Top-Down approach.
2
PP basically consists of writing a list of
instructions for the computer to follow, and
organizing these instructions into groups
known as functions.
3
This paradigm is:
Decide which procedures
you want; use the best algorithms you can
find.
4
Languages support this paradigm by providing
facilities for passing arguments to function and
returning values from functions.
5
6
7
8

Importance given to algorithms rather than


data.
Data move openly around the system from
function to function.
E.g. C, COBOL, FORTRAN.
Relationship of data and functions is:

Object oriented Programming


It is a Bottom-Up approach.
OOP allows decomposition of a problem
into a number of entities called objects
and then builds data and functions
around these objects.
This paradigm is:
Decide which classes
and objects are needed; provide a full set
of operations for each class.
Languages support this paradigm by
creating objects and send the messages
to them to use or manipulate the
attributes.
Importance given to data rather than
algorithms.
Data cannot move openly around the
system as the concept of data hiding is
involved.
E.g. C++, JAVA.
Organization of data and functions in
OOP:
Object A
Object B

Global Data

Function-1

Function-2

Data

Data

Functions

Functions

Communication

Local Data

Local Data

Object C
Functions

Data
9

The primary focus is on functions.

The primary focus is on objects.

10

It is suitable for creating medium size projects.

It is suitable for creating large size


projects.

11
12

It does not model real world problems very


well.
The complexity of the programs is very high.

It can model real world problems.


The complexity of the programs is less.

Top-Down programming
In the top-down design the overall task of the program is to break down a large programs into several
logics and then they are interested by calling these logics whenever necessary.
The top-down approach starts from a high level abstract solution of the given problem and work down
toward more detailed specific solution. In this, the over all task is just defined in terms of generalized
subtask, which are subsequently further, defined and so on. This process is continued downward until
the sub tasks are defined in a form suitable for execution by the computer.

Complex
Problem

Simple
Proble
m1

Even
Simple
Problem1

Simple
Problem
2

Simple
Problem
3

Even
Simple
Problem2

Advantages
1. It shows the sequential division of the problem from top to bottom, which is a generalized and
easy method.
2. Modules can be developed parallel.
3. Easy, quick and minimum error prone development programs.
Bottom-up Approach
Bottom-up programming is the opposite of top down programming. In bottom up approach all the
subtask are first coded into program and then interacted into increasingly larger modules of the
design, in the bottom up approach available set of modules are first identified. An attempt is made to
combine the lower modules/subprograms to form modules of a high level.
This process of combining modules is continued until the program is constructed. In this
approach quite after it is found that the final program obtained by combining the predetermined lowest
level modules does not meet all the requirement of the desired program.
In a language such as C++ or java, bottom up programming takes the form of constructing abstract
data types.
Advantages
1. The most important modules are written and tested first.
2. It is easier for users or customers to see the progress being made in the project.
3. Testing and debugging are easier and more efficient.

4.
5.
6.
7.
8.

The implementation is normally smoother and shorter.


Programmer moral and job static function are increased.
It is easier to detect and correct time delay and cost average runs.
It is easier to deal with time delays and cost overruns when they occur.
Data processing resources are used more evenly and efficiently.

Disadvantages
The basic drawback of the bottom up approach is the assumption that the lowest level modules can
be completely specified beforehand, which in reality is seldom possible.
Basic Concepts of Object Oriented Programming
1.

Object

2.

Class

3. Data Encapsulation and Abstraction


4.

Data Hiding

5.

Inheritance

6.

Polymorphism

7.

Dynamic binding

8.

Message Passing

1.

Object: Objects are the basic run-time entities in an object-oriented system. Programming
problem is analyzed in terms of objects and nature of communication between them. When a
program is executed, objects interact with each other by sending messages. Different objects can
also interact with each other without knowing the details of their data or code.
1. An Object is an Instance of a Class. An Instance is the existence in the computer system by
acquiring a memory space.
2. An Object is the only way a Class becomes usable.
3. Objects are basis of Object Oriented Programming.
4. An Object has all the Characteristics of the Class using which the Object is created.
5. It implements reusability of code written in Classes.

Object: student
DATA
Name
Date of birth
FUNCTIONS
Total
Average

2. Classes: A class is a collection of objects of similar type. Once a class is defined, any number of
objects can be created which belong to that 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.
1. A Class is a Blueprint or Stencil for creating Objects.
2. A Class specifies all the Member Data and Member Functions that would be present in the
Objects created using the Class.
3. Using a Class any number of Objects can be created.
4. Its a User Defined Data Type also called Abstract Data Type, which acts like a basic data type
when used.
5. Usually Classes are used to represent computer understandable formats for Real World
Entities.
3. Data Abstraction and Encapsulation
Abstraction refers to the act of representing essential features without including the background
details or explanations. Classes use the concept of abstraction and are defined as a list of
abstract attributes. Storing data and functions in a single unit (class) is encapsulation. Data
cannot be accessible to the outside world and only those functions which are stored in the class
can access it.
Abstraction :1. Its the process of Hiding the complexities of implementation and providing a simple Interface
for easy use.
2. Its implemented using Encapsulation.
3. Functions, Structures and Classes implement Abstraction at programmer level.
Encapsulation :1. Its the process of wrapping up of Data and Functions inside a single Entity (usually Classes).
2. Encapsulation helps to establish Abstraction and Data Hiding.
3. Functions, Structures and Classes implement Encapsulation at programmer level.
5.

Data Hiding :Its the process of keeping the Data under such an Access mode that its only accessible to
permitted Functions.Using Private, Protected specifiers, we can hide Data from access from
outside a Class. Functions, Structures and Classes implement Data Hiding at programmer level.

6. Inheritance
Inheritance is the process by which objects can acquire the properties of objects of other class. In
OOP, inheritance provides reusability, like, adding additional features to an existing class without
modifying it. This is achieved by deriving a new class from the existing one. The new class will have
combined features of both the classes.
1. Here the Class which gets the Inherited properties is called the Child Class and from which it
acquires the properties is called the Base or Parent Class.
2. During Inheritance the Protected and Public Data and Functions get passed on as copies from
the Parent or Base Classes to Child Classes.

3. It forms a Hierarchical Structure from Parent down to Children Classes.


4. It implements Reusability of Parent Class Data and Functions.
5. Structures and Classes can be used to implement Inheritance.
6. Types :- Single, Multilevel, Multiple, Hierarchical and Hybrid.

Bird
Attributes:
Feathers
Lay eggs

Flying Bird
Attributes:

Parrot
Attributes:
..
..

Nonflying Bird
Attributes:
..
.
Robin
Attributes:

..

Panguin
Attributes:

..

Kiwi
Attributes:

..

Fig. Property inheritance


7. Polymorphism
Polymorphism means the ability to take more than one form. An operation may exhibit different
behaviors in different instances. The behavior depends on the data types used in the operation.
Polymorphism is extensively used in implementing Inheritance using same name with either Different
number of Arguments or Different Data types of Arguments.
Types:- Compile Time (the compiler recognizes the binding between the function and its code during
compile time) and Run Time(the compiler recognizes the binding between the function and its code
during runtime)

8.

Dynamic binding :1. Its also called Runtime Polymorphism, where the compiler recognizes the binding between the
function and its code during runtime.
2. Its implemented using Virtual Functions, during Inheritance.

9.

Message Passing :1. Its the process of passing Data between Objects of same Class and also of different Classes.
2. Its implemented using Function calling or by simply sharing data.
3. Types:- From User to Objects (done by invoking Function inside an Object) and From Object
to Object (by sharing Data of one Object with another Object).
4. Using Friend functions (with objects as input arguments), message passing can be done
between two or more Objects of Different Classes.
5. Using member Functions (with objects as input arguments), message passing can be done
between objects of same Class.

History Of The C++: C++ is an Object Oriented Programming laguage.It was developed by Bjarne
Stroustrup at AT&T Bell Laboratories in Murray Hill New Jersy, USA, in early 1980s.

C++ is an extension of C with major addition of the class construct feature.

Stroustrup initially called the new languageC with Classes.

In 1983 the name was changed to the C++.

C++ is superset of the C.

Structure of the C++ Program :

Simple C++ Program

// my first program in C++


#include <iostream>
void main ()
{
cout << "Hello World!";

}
// my first program in C++
This is a comment line. All lines beginning with two slash signs (//) are considered comments
and do not have any effect on the behavior of the program. The programmer can use them to
include short explanations or observations within the source code itself. In this case, the line is
a brief description of what our program is.
C++ supports two ways to insert comments:
// line comment
/* block comment */

#include <iostream>
Lines beginning with a pound sign (#) are directives for the preprocessor. They are not regular
code lines with expressions but indications for the compiler's preprocessor. In this case the
directive #include <iostream> tells the preprocessor to include the iostream standard file. This
specific file (iostream) includes the declarations of the basic standard input-output library in C+
+, and it is included because its functionality is going to be used later in the program.
void main ()
This line corresponds to the beginning of the definition of the main function. The main function
is the point by where all C++ programs start their execution, independently of its location
within the source code. It does not matter whether there are other functions with other names
defined before or after it.This function's definition will always be the first ones to be executed
in any C++ program. For that same reason, it is essential that all C++ programs have a main
function.
cout << "Hello World";
This line is a C++ statement.This statement performs the only action that generates a visible
effect in our first program.
cout represents the standard output stream in C++.The operator << is called the insertion or
put to operator and the meaning of the entire statement is to insert a sequence of characters
(in this case the Hello World sequence of characters) into the standard output stream (which
usually is the screen).
We could have written:
int main () { cout << "Hello World"; return 0; }
Notice that the statement ends with a semicolon character (;). This character is used to mark
the end of the statement and in fact it must be included at the end of all expression statements
in all C++ programs.
Compiling And Linking : Compiling and linking a C++ program depends on compiler and operating
system.Turbo C++ and Borland C++ provide an integrated program development environment under
MSDOS .They provide built in editor and a menu bar which includes options such as File, Edit,
compile and Run.
C++ I/O statement:
C++ I/O operations are called streams. There are two types of streams in c++ they are
1. Input streams
2. Output streams

Input streams: input streams are used to read data from input devices like keyboard, hard disc, etc.
by using a predefined input stream object cin and >> extraction operator to read data from input
devices.
Syntax: cin >> var;
example: cin >> x ;
For example in the above statement the compiler wait for input data for variable x the input data is
then take from input device and then assigned to variable x. It is possible to read any type of data
using cin statement.The header file iostream.h must be included to use this statement in a program.
Input cascading operation:
Input cascading means read values of more than one variable of different data types using single
input statement.
Syntax: cin >> var1 >> var2>> var3;
Example: cin >> x>>y>>z; //where x, y, z may be of different data type
Output streams: output streams are used to print data on output devices like monitor, discs etc. by
using a predefined output stream object cout and << insertion operator to read data from output
devices.
Syntax: cout << var;
example: cout << x;
For example in the above statement the compiler prints value of variable x on output device. It is
possible to print any type of data using cout statement. The header file iostream.h must be included
to use this statement in a program.
Output cascading operation:
Output cascading means print values of more than one variable of different data types using single
output statement.
Syntax
cout << var1 <<var2<<var3:
Example
cout << x << y <<z; where x, y, z may be of different data type
Advantages of streams
1. Streams do not require explicit data types specification in I/O statement
2. Streams do not require explicit address operator prior to the variable in the input statement
3.
Data types: C++ data types can be classified as
1. Standard data types
2. Derived (extended data types)
3. User defined data types
The following figure represents the detail of c++ data type classification
Standard data types:
Standard data types are used to tell the compiler what type of data to be handled by an identifier.
These data types give complete details of the behavior of a data type. It is possible to handle only
one value at a time.C and C++ compilers supports the built in data types.With the exception of void
the basic data tyoes may have several modifiers(signed,unsigned,long,short) may apply to the
character and integer basic data types.

C++ DATA TYPES


User defined
Data type
Structure
Union
Class
Enum

Standard data types

Array
Pointer
Function

void
Integral type
int

Void: -

Derived
Data type

char

Floating type
float

double

The Void is used to represent the following things


To specify the return type of a function when it is not returning any value.
To indicate an empty argument list to a function.
Declaration of the generic pointer.

1)
2)
3)

User defined data types:


User defined data types are created by a user by using simple, derived, user defined data types as
per the user requirement. The user has to decide the functionality and behavior of these data types.
By using these data types to handle more than one data type using single identifier For example
structures and classes
Derived data types (extended data types):
Derived data types are used to extend the behavior of an existing simple data type to get more
functionality. It is possible to handle more than one value at a time using a single identifier. For
example arrays.
The following table gives the details regarding various data types.
Data Type

1)
2)
3)
4)
5)
6)
7)
8)
9)
10)
11)

Char
Unsigned Char
Signed Char
int
Unsigned int
Signed int
Short int
long int
float
double
long double

Size
Range
1
1
1
2
2
2
2
4
4
8
10

in

-128 to 127
0 to 255
-128 to 127
-32768 to 32767
0 to 65,535
-32768 to 32767
-32768 to 32767
-2147483648 to 2147483647
1.2e-38 to 3.4e38
2.2e-308 to 1.8e308
3.4e-4932 to 1.1e+4932

C++ Operators and Expressions


(i)
(ii)
(iii)

(iv)

Arithmetic Operators: (+, -, * , / , %)


Assignment Operators: (=, += , - = , *= , /=, %=)
Comparison and Logical Operators:
(a) Relational Operators (< , >, <= , >=)
(b) Equality Operator (==, !=(not equal to))
(c) Logical Operator (&& , || , ! )
Bitwise logical Operators:

bytes

(v)

&
Bitwise AND
^
Bitwise XOR
|
Bitwise OR
>>
Bitwise right shift
<<
Bitwise left shift
~
Bitwise complement
Special Operators
(a) Unary Operator
*
contents of the storage field to which a pointer is pointing.
&
Address of variable.
Negative Value.
!
Negation (0 , if value is not equal to 0, 1 , if value=0)
++
Increment
-Decrement
//type
Forced type of conversion
sizeof
size of the subsequent data type or type in byte
(b) Ternary Operato. r (?:)
exp1 ? exp2 : exp3
Eg max= ( first > second) ? first : second;
(c) comma operator ( , )
(d) Scope operator ( : : )
The double colon : : operator is used as the scope resolution operator in C+
+.A member function of the class is defined using the : : scooping operator.
Eg. #include<iostrean.h>
#include<conio.h>
int a=10;
void main()
{ int a=5;
cout<<a; // 5
cout<<: :a; // 10
}
#include<iostrean.h>
#include<conio.h>
class sample
{
public:
void input();
}
//return type of func classname: :memfunction
void sample : : input();
(e)new and delete operators: In traditional C the dynamic memory allocation and
deallocation are through library functions such as malloc, alloc, calloc and free.
C++ defines a new method for carrying out memory allocations and
deallocations i.e. using new and delete operators.
(f) Other operators
(a) Parenthesis for grouping expressions( () ).
(b) Membership operators ( [ ] , )

Type Conversion:
(a) cast operator.
(cast type) expression;
or

cast type (expression);


e.g a = (int) (19.2/4);
a = int (19.2/4);
Expressions: An expression is a collection of data objects and operands that can be evaluated to
a single value. An object is a constant , variable or any other expression.
e.g (5+6) * (5-8);
C++ control structures:
Control structures determine the direction or order in which statements within the block are executed.
Control
statements are used to design control structures. In CPP control statements can be classified as
1. Conditional control statements (if, if else, ladder if, switch .. case )
2. Iterative control statements ( for, while, do .. while)
3. Unconditional control statements (goto, continue, break)
(1) Conditional control statements:
Conditional control statements are used to control the flow of control based on condition statement.
For
example if , if else, switch etc.
If statement:
Syntax: 1. if (condition)
statement;
// simple if statement
2. if (condition )
// if else statement
Statement
else
Statement
3. else if (condition)
Statement
else if (condition)
Statement
else
Statement
The switch statement:
When there are a number of else alternatives as above, way of representing is by the switch
statement.
The general format of a switch statement is
Switch (expression)
{
case value1:
program statement

break;
case value2:
program statement

break;
case valuen:
program statement

break;
default:
program statement
break;
}

(2) Iterative control statements


for loop:
for (variable = initial ; condition; amount of increment/decrement)
{
Lines to be repeated;
}
while loop:
initial condition
while (condition)
{ stmt;
stmt;
change of the initial condition;
}
do while loop:
{ stmt;
stmt;
}
while (condition);
(3) Unconditional statements:
Unconditional statements are used to transfer the control from one place to other with out any
condition. They are generally used to branch or termination process. For example goto, break,
continue, and exit;
Syntax:

goto used to branch the control to a particular place


Break to terminate the iterative statements
Continue to get the next iterative value

Arrays in C++:
An array is a sequence of data in memory where in all the data are of the same type and are placed
in physically adjacent location.
(1) One dimensional.
(2) Two dimensional
(3) Multi dimensional
Array Declaration:
(1) Type of the array (i.e. integer , float , char type etc)
(2) Name of the array
(3) Number of subscript in the array ( one-D , two-D etc)
(4) Total number of memory location to be allocated
Syntax : storage_class data_type array_name[const]
int marks[10], a[12][10];
static char page[8];
int value [0];// invalid
char s[$]; //invalid

float num [-10]// invalid

Array Initialization:
(1) Compile time initialization
int marks [5] = { 1,2,3,4};
Marks[0] = 1
Marks[1] = 2

Marks[2] = 3

Marks[3] = 4

Marks[4] = 0

char name [4] = { R , E , N , U};


name[0] = R

name[1] = E

name[2] = N

name[3] = U

int x[2][2] = {1,2,3,4};


x[0][0] = 1 x[0][1] = 2

x[1][0] = 3

x[1][1] = 4

int A[3][3] = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
(2) Run time initialization
#define max 10
void main()
{
int marks[max];
for ( i= 0 ; i< max-1 ; i++)
{
cin>>marks[i];
}
}
#define N 4
#define M 4
void main()
{
int marks[N][M];
for ( i= 0 ; i<N-1 ; i++)
{
for ( j= 0 ; j<M-1 ; j++)
cin>>marks[ i ][ j ];
}
}
Character Type array :
When initializing a character array in ANSI C, the compiler will allow us to declare the array size as
the exact length of the string constant
char name[3]=red; // valid in ANSI C
But in C++ the size should be one larger than the number of characters in the string.
char name[4]=red; //o k for C++
Pointers in C++
A pointer is a variable which holds the address of any variable or a function. A pointer can refer to an
object of any one of the data type.
Pointer declaration:
Syntax : data type * variable_name; for example : int *x; or int* x; or int * x;
Pointer operator:

Pointer operator can be represented as * (asterik) with a variable name. For example if a variable of
integer data type and also declared * with another variable, it means the variable is of type pointer to
integer.
int *ptr ;
float *fptr;
char *cptr;
Address operator:
An address operator can be represented by the use of & (ampersand). The operator immediately
preceding a variable returns the address the of the variable.
E,g int a;
Int *p;
p = &a ; or int *p = &a; // address of variable a is assigned to pointer variable p.
& operator can be used only with a simple variable or an array element .
E.g &120 ; //invalid
int x[10];
&x;
//illegal use of ampersand operator.
&x[0] or &x[i]
//valid;
Constant pointer: C++ adds the concept of constant pointer and a pointer to a constant.
char * const ptr1=GOOD;
// constant pointer
we can not modify the address that ptr1 is initialized to.
int const * ptr2 = &m; // pointer to a constant
ptr2 is declared as pointer to constant> It can point to any variable of correct type but the contents
of what
it points to cannot cannot be changed.
We can also declare both the pointer and the variable as constants in the following way:
Const char * const ptr = xyz;
This statement declares ptr as a constant pointer to the string which has been declared a constant.
In this case neither the address assigned to the pointer ptr nor the contents it points to can be
changed.
Void pointer:
Syntax: void *variable
for example: void *x;
The void type of pointer is a special type of pointer; void pointers are pointers that point to a value
that has no type. This allows void pointers to point to any data type, from an integer value or a float to
a string of characters.
int .a;
char c;
void *p;
p = &a;
cout<< Value of a= , *((int *)p); //void pointer is typecasted to int type.
Null pointer:
A null pointer is a regular pointer of any pointer type which has a special value that indicates that it is
not pointing to any valid reference or memory address. This value is the result of type-casting the
integer value zero to any pointer type.
Syntax:
data type * variable = NULL or
data type *variable = 0
For example int *x = 0
or int *x = NULL:
Pointer Arithmetic:
ptr-- : Decrements the value by the size of the data type.
ptr++: Increments the value by the size of the data type.
--ptr : Decrements the value by the size of the data type before the statement is executed.
++ptr : Increments the value by the size of the data type before the statement is executed.
*ptr--: Retrieve the contents of location pointed by pointer then decrement the pointer.
*--ptr: Decrement the pointer then retrieve the contents of new location pointed by pointer.

*ptr++:
*++ptr:
--(*ptr):
(*ptr)--:

Retrieve the contents of location pointed by pointer then increment the pointer.
Increment the pointer then retrieve the contents of new location pointed by pointer.
Decrement the contents pointed by pointer by one then retrieve the new value.
First retrieve the content pointed by pointer , then decrement the content by one pointed by
pointer.
++(*ptr): Increment the contents pointed by pointer by one then retrieve the new value.
(*ptr)++: First retrieve the content pointed by pointer , then increment the content by one pointed by
pointer.
Reference Variable: C++ introduces a new kind of variable known as the reference variable. A
reference is an alias or an alternative name for an existing variable. All operations applied on
reference variables are also applied on original variable. The address of a reference variable is same
as the address of the original variable. Reference variable looks like ordinary variable and behaves
like pointer variable. A reference variable can be defined as:
Datatype &ref_varible = ori_varible;
Eg

int a=5;
int &b = a;
cout<<a<<b; // output will be 5 5.
b= 20;
cout<<a<<b; // output will be 20 20.
Where b is a reference variable of a and a is a referent.
The following points can be noted about reference parameters.
A reference can never be null. It must always refer to a valid object or variable
Once a reference variable is created for one variable it cannot be reference variable for
another variable.
Reference never takes any extra space in memory.
Reference has to be initialized while declaring only.
Limitation: A variable(referent) can have more then one references but one reference variable can
have
only one referent.
Difference between Pointer variable and Reference variable.

Pointer Variable
1. It is a special variable which can store

Reference Variable
It is a duplicate name (alias) given to any

the address of another variable


2. Here the Pointer variable will be created

variable.
No extra space is required. Only a

in the memory and then it can be


assigned any address.
3. Using * or de-referencing operator

duplicate name is assigned to the same


memory area.
By simply using an

or assignment

along with the pointer variable the

operator with the reference variable the

value inside the address can be

value can be changed

accessed
4. Used while implementing Call By

Used

Address
5. Common Syntax :-

Reference
Common Syntax :-

while

implementing

Call

By

Declaration :-

Declaration :-

Data type *Pointer variable name ;

Data type & reference = variable ;

Acquiring address :-

Here the LHS reference name given

Pointer variable = & variable name ;

would become the duplicate name for the

Here the address of the variable would

variable in the RHS

be stored get stored in the pointer

Manipulating data :-

variable .

reference = value ;

Manipulating data :-

here the value would be assigned to the

*Pointer variable = value;

variable , which would be reflected in both

here the value would be assigned to

the reference as well as the original

the variable name .


6. Example:-

variable.
Example :-

int a = 10 ;

int a = 10;

int *p ;

int &b = a;

cout<< a ; // it would show 10

cout << a << b ; // It would show 10 10

p = &a;

b=20;

*p = 20;

cout << a << b ; // It would show 20 20

cout<< a ; // it would show 20


Functions in C++ : A complex parts may be decomposed into a small or easily manageable parts or
modules called functions. Functions are very useful to read, write, debug and modify the complex
program. Functions are used to implement reusability of code .
The main Function: In C++ the main() function returns a value of type int to the operating system.
int main()
{

.
return 0;
}
Steps of writing Functions :-

1. Function Prototyping :- Here we write the Function prototype, which represents the name of
function, number of input arguments and data-types of input arguments. The prototype describes the
function interface to the comiler.
Syntax :- return-data-type function-name ( input-argument-list along with their data-types) ;
Example :- int add (int, int) ;
2. Function Definition :- Here we use along with the prototype, Opening and Closing curly brackets,
inside which we write the code of the function.
Syntax :- return-data-type function-name ( input-argument-list along with their data-types)
{ . }
Example :- int add (int a, int b) { return (a+b) ; }
3. Function Calling :- Here we use the function prototype, with out the return type and passing in the
real arguments. It causes the function to execute its code.
Syntax :- function-name ( argument-values) ;
Example :- add (10 , 20 ) ;
return statement: The keyword return is used to terminate the function and return a value to its
caller. The return statement may also be used to exit a function without returning a value. The return
statement may or may not include an expression.
Syntax:- return;
return (expression);
Categories of functions: A function depends on whether argument is present or not and whether a
value is returned or not.
Function with no argument and no return value.
void add ( void );
void main( )
{
add ( );

// function prototype
// function call.

}
void add (void)
// function definition
{ int a=10 , b=20;
cout<<addition is=<<a+b;
}

Function with arguments but no return value. E.g void add ( int a , int b )
void add ( int , int );
// function prototype
void main( )
{ int a,b;
cout<<enter value of a and b;
cin>>a>>b;
add (a,b);
// function call, a and b are actual arguments.
}
void add (int c, int d)
// function definition , c and d are formal arguments.
{
cout<<addition is=<<c+d;
}

Function with arguments and a return value. E.g int add ( int a , int b ).

int add ( int , int );


// function prototype
void main( )
{ int a,b, sum;
cout<<enter value of a and b;
cin>>a>>b;
sum= add (a,b);
// function call, a and b are actual arguments.
}
int add (int c, int d)
// function definition , c and d are formal arguments.
{ int e;
e = c + d;
cout<<addition is=<<e;
return( e) ;
//u can also pass expression like return( c+d)
}

Function with no argument but returns a value. E.g int add ( )

int number( void )


{ int m = number( );
cout<<value is: <<m;
getch();
}
int number(void)
{ int i;
cin>>i;
return(i);
}
Function that returns multiple values. //done by call by address.

Actual Arguments: An actual argument may be variable name , expression or constants contained in
a function call that replaces the formal parameter which is part of the function declaration.
Formal Arguments: formal arguments are the parameters present in function definition which may
also be called as dummy arguments or the parametric variables . Formal arguments must be a valid
variable name. When function call is made only a copy of the values of the actual argument is passed
to the called function. Any changes in formal argument does not effect the actual argument.
Parameter passing mechanisms in C++:The parameters can be passed in 3 ways in C++. They are
1) Call by value 2) Call by address
3) Call by reference
Call by value: In C++ by default a function call passes parameters by value
In this mechanism the values of actual parameters will be passed to a separate set of
variables known as formal parameters
The formal parameters of type value parameters
Any changes made to formal parameters will not affect the corresponding actual
parameters.
Only one value to be return from function
e.g void main ()
{
void swap (int, int); // function prototype
int a=10,b=50;
swap(a,b);
// function call as call by value
cout<<a<<b;
// 10 50
}
void swap (int x, int y) // function definition.

int t; t=x;
cout<<x<<y;

x=y; y=t;
// output 50 10

}
Call by address:In C++ it is possible to call a function by passing address this technique is known as call by address.
In call by address technique the formal parameters must be a pointer type and they
receive the addresses of actual parameters.
Any changes to the formal parameters are automatically reflected back to the actual
parameters in the main program.
It is possible to make a function to return more than one value to the calling program
The address can be generated by using address operator &.
e.g

void main ( )
{
void swap (int * , int * ); // prototype
int a,b;
a=50; b=30;
swap(&a,&b);
/*call by address*/
cout <<a<<b<<endl;
}
void swap (int *p1, int *p2) / *Receiving the addresses in pointers*/
{
int t; t=*p1; *p2= *p1;
*p2=t; }
From the above example, it is clear that the main() function can display the swapped values of a and
b.
Call by Reference: The formal parameters must be of type reference
When we pass parameters by reference the formal parameters becomes like an alias
variable to the formal parameters
To pass arguments by reference, the function call is similar to that of call by value. Ex
swap(a,b)
In the function decelerator the formal parameters are preceded by the & operator.
It is possible to return more than one value from a function to the main program
Any changes to the formal parameters are automatically reflected back to the actual
parameters in the main program.
Using this method no duplicate set of variables are crated.
Hence the complete program of swapping 2numbers using call by reference can be shown as follows.
void main ( )
{
void swap (int &x, int & y);
int a,b;
a=50; b=30;
swap(a,b);
// function calling.
cout<<a<<b<<endl;
}
void swap(int &x, int &y)
{
int t; t=x;
x=y; y=t;
}
Example: Square of two numbers using call by value, call by address and call by reference.
(i) call bye value:
void main( )
{ void square ( int , int );
// function prototype
int a,b;
cout<<enter value of a and b;
cin>>a>>b;

square(a,b);

// function call, a and b are actual arguments.

}
void squre (int c, int d)
// function definition , c and d are formal arguments.
{
cout<<square is=<<c*c<<d*d;
}
(ii) call bye address:
void main( )
{ void square ( int *, int *);
// function prototype
int a,b;
cout<<enter value of a and b;
cin>>a>>b;
square(&a, &b);
// function call, a and b are actual arguments.
cout<<a<<b
// square values
}
void squre (int *p1, int *p2)
{
*p1=(*p1) * (*p1) ; *p2=(*p2) * (*p2) ; }
(iii) call by reference:
void main( )
{ void square ( int & , int &);
// function prototype
int a,b;
cout<<enter value of a and b;
cin>>a>>b;
square(a, b);
// function call, a and b are actual arguments.
cout<<a<<b
// square values
}
void squre (int &x, int &y)
// function definition , x and y are reference variable.
{
x= x*x ;
y=y*y ; }
There are Three categories of Calling Functions in C++
1. Return by Value :1. Here the value returned by the function after it is executed is a simple value.
2. Example :int greater(int a, int b)
{
if ( a > b)
{ return a ; }
else
{ return b ; }
}
main()
{
int i, j ;
cin >> i >> j ;
cout << Greater Value is:- << greater ( i , j );
}
2. Return by Address : 1. Here the returned value is an address, and has to be received in a pointer.
2. Example :int* fill (int *p)
{
p = new int [5] ;
for ( int j = 0 ; j < 5 ; j ++ )
{
cin >> p [ j ] ; }
return p ;

}
main()
{
int *q;
q = fill ( q ) ;
for ( int k = 0 ; k < 5 ; k ++ )
cout<< q [ k ] ;
}
3.

Return by Reference :1. Here value returned is the reference to a variable.


2. Example :int& greater(int & r, int & j)
{
if ( r > j )
{ return r ;
}
else
{ return j ;
}
}
main()
{
int a = 10, b = 5 ;
greater ( a , b ) = 100 ; // Here the reference to the greatest of a and b will be
returned
and will be assigned the value 100
cout<< a << b ; // output 100 5
}

Inline functions: Function execution involves the overhead of jumping to and from the calling statement. Trading of this
overhead in execution time is considerably large whenever a function is small. Hence in such case
inline functions are used. Inline functions are those whose function body is inserted in place of the
function call statement during the compilations process. An inline function definition is similar to an
ordinary function, except that the keyword inline precedes the function definition.

By default every function created in C++ is Inline.


The syntax for defining an inline function is as follows:
inline function- header ( )
{
Body of the function;
}
eg. inline float getdata (int a, float b)
{
return (a+b); }
void main ()
{
int a= 35;
float b= 18.5;
cout <<The sum is <<getdata (a,b);
}
The inline functions are similar to macros in c language. But the major drawback with macros is that
the error checking does not occur during compilation.
The following are the situations where inline functions may not work properly
1. Functions returning values, having a loop, a switch or a go to exists
2. If the function contains static variables.
3. If inline functions are recursive.
Disadvantages: 1. In line functions may require more memory in the program as they are basically expanded
while compiling the program.
2. The speed benefits of inline functions diminish as the functions grows in size.

The inline key word sends a request but not a command to the compiler. Hence the compiler can
ignore the request if the function definition is too long.
Default arguments: In c++ default arguments are used to call a function without specifying all of its arguments. In the
function prototype declaration the default values are given. Whenever a call is made to a function
without specifying an arguments, the complier will automatically assign values to the parameters from
the default function prototype declaration. A default argument can in the function prototype. Once it is
defined, it cannot be redefined at function definition argument list .
Some points regarding default arguments;
1) A default argument is checked at the time of declaration and evaluated at the time of call.
2) Default argument is used only when any argument value is missing at function call.
3) We must add the default parameters from right to left.
4) We cannot provide a default parameter in the middle of an argument list
5) Default arguments are useful where some arguments always have the same value
For example: float amount (float principle, int period, float rate = 0.15);
Note: - principle, period are general formal parameters, rate is Default argument.
For ex: the function call
Value= amount (5000, 7); // one argument missing hence default value will be taken.
The above function call passes
5000 principle
7
periods
Then the function use the default value for rate parameter as 0.15
rates.
e.g. void sum( int , int x=10, int y=20); // function prototype with default argument list.
void main()
{ int a=5,b=15,c=5;
sum(b); //
if we call the function like sum(a,b,c) then there is no use of default arguments.
------------}
void sum( int a1, int a2, int a3)
//function declaration
{ int temp;
temp = a1+ a2+a3; // a2=10 a3=20 by default arguments. I.e temp=45
}
Const arguments :1) Here we declare the arguments as constants by using const keyword, in the function
definition.
2) The arguments declared as const cannot be changed in side the function definition.
3) During calling of the function the const arguments would acquire the values initially given in the
call.
4) Syntax :- return-type function-name ( const argument, . ) { function definition code }
5) Example :main( )
{ void get(int, const int);
add( 5 , 5 ) ;
getch();
}
void add ( int a , const int b )
{
a=10; // can be reinitialized because it is a simple variable.
b=20 ; // Not allowed as its declared const
cout << ( a + b ) ; // output 15
}

Function overloading:Function overloading can be defined as define a set of functions having same name and different
signatures. The same function name will be used with different number of parameters and parameters
of different type. We can use the same function name to create function that performs a variety of
different tasks. This is known as function overloading (function polymorphism) in OOP. The function
can perform different operations depending on the argument list in the function call. At the time of
calling correct function to be invoked is determinates by checking the number and type of the
argument but not on the function return type.
For ex an overloaded add( ) function handles different types of data as follows.
void max (int a, float b); // prototype 1
void max(int a, int b, int c); // prototype 2
void max (double x, double y);// prototype 3
void max(float p, int q); // prototype 4
The following function calls can be given in the program
x= add (0.75,5);//uses prototype 4
y= add (5,10,15);// uses prototype 2
z= add (5,10.5);//uses prototype 1
p= add (12.5,17.5); // uses prototype 3
Rules that govern the usage of function over loading:
1. The compiler first tries to find an exact match, in which the type of actual parameters are the
same and use that function.
2. If an exact match is not found then the compiler converts the arguments as follows.
i. char to int
ii. float to double
iii. int to float
iv. All these conversions take place to find a match.
3. Some times compiler generate ambiguity errors because the compiler may not be able to
decide what signature function should be called. If the conversion is possible to have multiple
matches then the compiler generates an error message. Suppose we use the following 2
functions.
long square (long n);
double square (double x);
A function call such as square (100) will cause an error because int argument 100 can be
converted to either long or double. The following is an ex: program that shows the usage of
function overloading
#include <iostream.h>
#include <iomanip.h>
void main()
{ float area (int r); // over loaded function
int area (int l, int b);
//over loaded function.
float a;
int a1,l,b,r , a1 ;
cout <<enter the radius of the circle <<endl;
cin>>r;
a=area(r);
cout << area of the circle is <<a<,endl;
cout <<enter the length and breadth of the rectangle;
cin>>l>> b;
a1= area(l,b);
cout<<area of the rectangle is <<a1<endl;
float area (int r)

{
return (3.141*r*r);
int area (int l, int b)
{
return (l*b);
}

UNIT-II

Classes And Objects


Structure
Structure can be defined as a
collection of dissimilar data items.
Contains only data member
By default all members are public
The size of the structure = size of
the individual data items of a
structure
Separate copy of data members are
created for all structure variables
To create a structure variable use
keyword struct
It is Not possible to inherit structures
Structure are called as Passive data
item

Class
Class can be defined as
combination of data items and
functionality applied on that data
Contains data members and
member function applied on that
data
By default all members are private
The size of the structure = size of
the individual data items of a class
Separate copy of data members and
only one copy of member functions
are created for class
To create a class variable the
keyword class is optional
It is possible to inherit class
Classes are called as Active data
items

Class: Class can be defined as combination of data members and member functions applied on that
data. It allows the data to be hidden from the external use. A class can also be called as an abstract
data type (ADT).
Abstract Data Type can be defined as the technique of creating new data types whose
implementation details are hidden and can only be handled using the publicly accessible member
function
Its a User Defined Data-type.
1.The Data declared in a Class are called Data-Members of the Class.
2.The Functions declared or defined in a Class are called Member-Functions of the Class.
The members of a Class can only be accessed through Objects of the class.
Syntax: class class_name
for example
{
class a
access specifier:
{ private;
member1;
int x
access specifier:
public :
member
void show() {cout <<
function;
a;}
...
};
} [object_name];
Where class_name is the name for a class (user defined type) and the optional field object_name is
one, or several, valid object identifiers. The body of the declaration can contain members, which can
be either data members or member functions.
The following are the characteristics of a class
The keyword class specifies abstract data type of type class name.
The body of a class is enclosed with in braces and terminated by a semicolon

The functions and variables with in the class are collectively called as members
The members that have been declared as private can be accessed only from with in the class.
Class definition is only a template and does not create any memory space for a class
By default all the members are of type private .

Three Access Specifiers :


Public :
Any member declared under this specifier is Accessible from Outside the
class, by using
the object of the Class.

The Public members of a Class get Inherited completely to the Child Classes.

The keyword public : is used.

Syntax :Class definition


{
public :
declarations or definitions
};

Example :class A
{
public :
int a;
};
main()
{
A oba ;
oba . a = 10 ; // we have set the value of variable a in object
oba to 10
}

Private :
Any member declared under this specifier is Not Accessible from Outside the
Class.

The Private members are accessible to only the Member Functions and Friend
Functions
in the Class.

The Private members of a Class Never get Inherited to the Child Classes.

The keyword private : is used.

Syntax :Class definition


{
private :
declarations or definitions
};

Example :class A
{
private :
int a;
public :
void fill ( )
{ cin >> a ;
}
};
main()
{
A oba ;
//
oba . a = 10 ; // invalid as a is private member.
oba . fill ( ) ; // valid as fill ( ) is a public member.
}

Protected :-

Any member declared under this specifier is Not Accessible from Outside the
class, by using the object of the Class.
The Protected members of a Class get Inherited completely to the Child
Classes and they maintain their Protected visibility in the child Class.
The Protected members are accessible to only the Member Functions and
Friend Functions in the Class.
The keyword protected : is used.
Syntax :Class definition
{
protected :
declarations or definitions
};
Example :class A
{
protected :
int a;
public :
void fill ( )
{ cin >> a ;
}
};
main()
{
A oba ;
//
oba . a = 10 ; // invalid as a is protected member.
oba . fill ( ) ; // valid as fill ( ) is a public member.
}

Member function defined outside the class definition:


1. To declare the member function of a class outside the class definition the function prototype
declared within the body of a class and defined them out side the body of a class.
2. Member ship identity label (class_name :: ) differentiate member functions and non member
function in a program.
3. By default the member function defined outside the class definition is non-inline.
4. To make it inline by explicitly adding inline as prefix to the member function in the definition.
syntax
class classname
{ access specifier:
return data type functionname(arguments);
//declaration
};
return data type classname ::
functionname(argument) // function definition
{
function body;
}

for example:
class a
{ public;
void show(); // prototype
};
void a:: show()
{ cout << this is outside the class ; }

Here the membership label class_name:: tells the compiler that the function is the member of the
specified class. The scope of the function is restricted to only the objects and other members of the
class.
To make the member function defined out side the class as an inline by adding inline as a prefix to the
member function.
Syntax
Return data type inline class_name :: function name(arguments)
{
function body ;}
The following are the properties of a member function.

Several different classes can use the same function name; the membership label will resolve
their scope
A class can have multiple member functions with the same name as long as they differ in
terms of argument specification (data type or number of arguments)
Member functions can access the private data of the class, but a non-member function
cannot.
A member function can call another member function directly, without using a dot operator.
There is no need to used member of operator (.) to access data members or member function
of a class within the class definition.

Objects:
Object can be defined as an Instance of a class. The process of creating objects (variables) of the
class is called class instantiation. In C++ the class variables are called as objects. The complier
allocates required memory for objects. The size of an object is equal to the sum of the sizes of the
individual data items of a class. The following is the general syntax of declaring objects.
Type1: class class_name ob1,ob2,ob3........obn;
Type2: class_name obj1.obj2,obj3,objn;
Where
class_name is the name of the class for which we want to create objects.
ob1, ob2,.... obn are the objects of class name.
Accessing class members:To access members of a class using the member off operator dot ( . )
It is not possible to access private data members of a class out side the class definition using dot
operator
The member access operator is not required to access data members within the class definition.
Syntax for accessing members of a class:
Access data members:
object_name.datamember;
For Pointer Objects :
Pointer-Object-Name -> member-name ;
Access member functions: object_name.memberfunction(actual_parameters);
The following is an example of creating an object of type item and invoking its member function.
void main ( )
{
item x; // creating an object of type item
x. getdata (20,20.5);
x put data ( );
}
Memory allocation for objects:For each object of a class a separate copy of data members and one copy of member functions is
created. For each object a separate memory is allocated and the address of that memory is stored in
this pointer. By using this pointer the unique copy of member function of all the objects of a class are
identified. This pointer is passed automatically to all the member functions of a class.

Exapmle:
#include<iostream.h>
#include<conio.h>
class sample

{ public:
int a ;
void get()
{ cout<<"\nenter any no:";
cin>>a; }
void show()
{ cout<<"\n value of a="<<a; }
};
//sample a1,a2;
class try
{ public:
int b;
void show()
{ cout<<"enter value of b:";
cin>>b;
cout<<"value of b is"<<b;
a1.a=202;
// undefined symbol a1
a1.show();
//undefined symbol a1
}
};
try i1;
void main()
{ sample a1;// if we create object of class here then we can not access its members in class try.
clrscr();
i1.show();
a1.get();
a1.show();
getch();
}
Exapmle 2:
void main()
{
clrscr();
class sample
{ private:
int a ;
void show()
{ cout<<"\n**value of a="<<a;
cin>>a; }
};
sample a1,a2;
a1.show(); //error ,although the calss is define inside the main() but its members are private ,so
cannot
getch();
accessible outside of the class.
}
Global class: A class is said to be global class if its definition occurs outside the bodies of all
functions in a program.
class sample
{ public:
int a ;
void get()
{ cout<<"\nenter any no:";

cin>>a; }
void show()
{ cout<<"\n value of a="<<a; }
}; sample s1 ;
// global object
void main()
{ sample s2 ;
//local object of a global class
s1.get();
s1.get(); s2.get(); }
Local Class: A class is said to be local class if its definition occurs inside the functional body.
void main()
{ class sample
//local class
{ private:
int a ;
void show()
{ cout<<"\n**value of a="<<a;
cin>>a; }
};
sample a1,a2;
// local objects
a1.show();
//error ,although the calss is define inside the main() but its members are
private ,so cannot
getch();
accessible outside of the class.
}
NOTE: A global object can only be declared using a global class type, while local objects can be
created from both class type i.e global as well as local.
Nested Class :1. Nested Classes are the Classes defined inside a Class.
2. A class is defined within another class is called a nested class.
3. The Outer class is known as enclosing class.
4. Member function of a nested class have no special access to members of an enclosing class.
5. Member function of an enclosing class have no special access to members of a nested class.
6. Object of inner class can be created by using : : operator.
Outer_class: : inner_class obj1;
7. The member function of the nested(inner ) class can be defined outside its scope.
Return_type of fun outer_class: : inner_class: : fun() { }
#include<iostream.h>
#include<conio.h>
class sample
{
public:
int a;
class inner
{ public:
int b;
void get_in()
{
cout<<"enter valueof b:"; cin>>b; }
}i2;
void show_out()
{
i2.b=100;
cout<<"\n**value of a=";
cin>>a;
cout<<"value of b="<<i2.b; }
};
sample a1;
sample: :inner i1;
void main()
{
clrscr();

a1.show_out();
i1.get_in();
i2.get_in();
//undefined symbol i2
getch();
}
Note: if we declare the inner class under private access specifier.
class sample
{ private: int a;
class inner
{ public: int b;
void get_in()
{ }
}i2;
public: void show_out()
{ }
};
although its define under private access specifier ,but its members are public.its members wont be
accessible when we declare them under private access specifer.
e.g class inner { private: int b; void get_in() { } }i2;
Example of nested class:
#include<iostream.h>
#include<conio.h>
class sample
{
private: int a;
class inner
{ public:
int b,c;
void get_in()
{ cout<<"enter value of b,c";
cin>>b>>c; }
void show_in()
{ cout<<"b="<<b<<"c="<<c; }
};
public:
void get1()
{ cout<<"enter a";
cin>>a; }
void show1()
{ cout<<"a="<<a;
inner i1;
i1.get_in();
i1.show_in(); }
};
sample a1;
void main()
{
clrscr();
a1.get1();
a1.show1();
getch();
}
Static data members :1. Only a single copy of the Static data members are shared between Objects of the Class.
2. Static data members are initialized using the data type Class-Name and Scope-Resolution
Operator and data member-Name
3. The Static members are declared using static keyword.
4. The access rule of the data members of a class is same for the static data member also.
5. The Static Data Members should be created and initialized before the main function control block
begins.

6.

Syntax :
For variables :- static data-type variable-name ;

#include <iostream.h>
#include<conio.h>
class sample
{
static int a;
// declaration
public:
void incr( )
{
a=a+1; }
void putdata ( )
{
cout <<"a="<<a<<endl;
}
};
int sample::a;
//by default initialize with 0
void main ( )
{ sample x,y,z;
y. incr ();
z.putdata( );
}
Example:
#include<iostream.h>
#include<conio.h>
int g=10;
class sample
{
int a;
public :
static int b;
void show()
{
b++;
cout<<"\nb = "<<b;
}
}s1,s2;
int sample :: b;
class other
{ int c;
public:void value()
{ s1.b+=2;
cout<<"\n--b--="<<s1.b;
}
} o1,o2;
void main()
{
clrscr();
s1.show() ;
o1.value();
s2.show();
o1.value();
getch();
}
output:
b=1;
--b--=3
b=4
--b--=6

s1

s2

void show()
b

Static member function:Like static member variables we can also have static member functions. A member function that is
declared as static has the following properties.
1) A static member function can have access to only other static members(functions or variable)
declared
in the same class.
2) A static member function can be called using the class name a follows.
a. Class_name : : function_name ( )
3) A static member function also calls the class constructor explicitly.
4)
The differences between a static member function and non-static member functions are as
follows.
A static member function can access only static member(data and member functions) data
and functions outside the class. A non-static member function can access all of the above
including the static data member.
A static member function can be called, even when a class is not instantiated, a non-static
member function can be called only after instantiating the class as an object.
A static member function cannot be declared virtual, whereas a non-static member
functions can be declared as virtual
A static member function cannot have access to the 'this' pointer of the class.
A static or non static member function cannot have the same name.
#include<iostream.h>
#include<conio.h>
class test
{
int code;
static int count ;
public:
void setcode( )
{
code =++ count;
}
void showcode ( )
{cout<<"object_number"<< code<<endl ;
}
static void showcount ( ) // static member function.
{
cout <<" count" <<count<<" \n";
cout<<code =<<code
//error , code is a non static member
function.
}
};
int test :: count;
void main ( )
{
test t1,t2,t3;
t1. setcode ();
t2. setcode ();
test :: showcount ( );
t3. setcode ( );
test:: showcount ( );
t1. showcode ( );
t2. showcode ( );
t3. showcode ( );
}
Output: count : 2

count : 3

object number :1object number : 2 object number : 3

Code

code

code

t1

t2

t3

3
showcode()

count
showcount()

setcode()

Friend Functions :1.


Friend functions are Not member functions of any class, but they can access the private,
protected and public members of the class.
2. They are declared using friend keyword.
3. They Dont belong to any specific Class.
4. They can be invoked as ordinary functions, with out using any object.
5. They can be defined outside the Class, here also they are defined like ordinary functions and
Not like member functions.
7. The access specifiers does not effect the visibility of Friend Functions.
8. Usually a friend function receives the object as arguments.
9. Syntax :friend return-type function-name ( input-arguments ) ;
10. member function of one class can be defined as friend function of another class.In such case they
are
defined using scope resolution operator as shown below.
class X
{
int fun1(); //member fun of X
};
class Y
{ ..

friend int X: :fun1();


};
Example:
#include<iostream.h>
#include<conio.h>
class sample
{ int a,b;
public:
void get()
{ cin>>a>>b; }
void show()
{ cout<<a<<b; }
friend void swap(sample s);
};
void swap( sample s1)
{ int temp=s1.a;
s1.a =s1.b;
s1.b = temp;
cout<<a=<<s1.a<<b=<<s1.b;

}
void main()
{ clrscr();
sample s2;
s2.get();
cout<< before swapping:<<endl;
s2.show();
cout<<After swapping:
swap(s2);
//function call swap(s2) passes the object s2 by value to the friend function.
getch();
}
Note: Actual swapping can be done by reference or address, we can make friend void swap( sample
&); or swap( sample *);
Example 2: swapping the data members of two classes using friend function.
#include<iostream.h>
#include<conio.h>
class second; // Forward declaration to satisfy the compiler about class B
class first
{ int a ;
void get()
{ cout<<"enter the value of a:";
cin>>a;
}
friend void swap ( first &,second &) ;
};
class second
{
int b ;
void get()
{ cout<<"enter the value of b:";
cin>>b;
}
friend void swap ( first &,second &);
};
void swap ( first &ob1,second &ob2 )
{ ob1.get();
ob2.get();
int temp;
temp = ob1.a ;
ob1.a = ob2.b ;
ob2.b = temp ;
cout<<"a="<<ob1.a<<"\nb="<<ob2.b;
}
void main()
{
clrscr();
first ob1;
second ob2;
swap(ob1,ob2) ;
getch();
}
Example 3: Finding greatest between data member of one class and another class by making
the member function of one class as a friend function of another class.
#include<iostream.h>

#include<conio.h>
class second; // Forward declaration to satisfy the compiler about class B
class first
{ int a ;
void get()
{ cout<<"enter the value of a:";
cin>>a;
}
public: void greatest(second);
};
class second
{
int b ;
void get()
{ cout<<"enter the value of b:";
cin>>b;
}
friend void first:: greatest(second);
};
void first::greatest (second ob2 )
{ get();
ob2.get();
if(a>ob2.b)
cout<<"greatest is"<<a ;
else
cout<<"greatest is:"<<ob2.b;
}
void main()
{
clrscr();
first ob1;
second ob2;
ob1.greatest(ob2) ;
getch();
}
Friend classes :
We can also declare all the member function of a class as friend function of another class using
friend class.
Eg
class first
{
friend class second;
};
class second
{ .
.
}

UNIT-III
Constructor:

1. Its a special function which has the same name as that of the Class name.
2. It has No Return-Type, not even void
3. It should have public or protected access within the class and rarely declared
as private.
4. Constructor overloading is possible.
5. Constructors cannot be virtual.
6. It can not be static.
4. Default arguments are possible.
5. They are invoked automatically as soon as Objects of Class are created.
7. We can explicitly call Constructors of a Class.
8. it is possible to have more than one constructor in a class.
7. They can Not be Inherited.
9. There are Three Basic Categories of Constructors.
a. Default Constructor: It takes no parameters and performs no
processing other than reservation of memory. It will always call by the
compiler, if no user defined constructor is being provided.
Syntax :- class-name ( ) { code } ;
b. Parameterized Constructor
Syntax :- Syntax :- class-name ( parameter-list ) { code } ;
c. Copy Constructor.
Syntax :- class-name ( reference of the same class) { code } ;
10. If in any Class the Default Constructor is not defined then the compiler
calls the implicit Default Constructor for Initializing objects of the Class. If
there exists a Default Constructor defined in the Class then the defined
Constructor will be called.
11. If any of the three categories of Constructors are defined in the Class then
the compiler in any case would never use the implicitly created Constructor,
it would only use the user defined Constructor.
Default constructor:
class sample
{ int a, b;
public:
sample()
{ a=0;b=0;
}
void show()
{ cout<<a<<b;
}
};
void main()
{ sample s;
s.show();
}
Destructors :1. Its a special function which has the same name as that of the Class name.

2.
3.
4.
5.
6.
7.
8.
9.
9.

It has No Input-Arguments and No Return-Type, not even void.


Its definition is preceded by Tild symbol ~ .
Its called implicitly as soon as the scope for any object finishes. Its invoked
for every object .
The compiler creates a Destructor for every Class implicitly by default.
If a Destructor is explicitly defined then the compiler will always use the
explicitly defined Destructor.
Its generally used to free up the spaces allocated by using new operator
during calling of Constructors. The de-allocation should be done using
delete operator
The object that is created First is Destructed Last and object created Last
is Destructed First.
Syntax :- ~class-name ( ) { code }
Example :Write a program to count the number of Objects created and destroyed using
constructor and destructor functions. The objects should be identified by a
unique ID, which should be mentioned while creation and destruction of the
object.
class sample
{
static int count;
int a;
public:
sample()
//Constructor
{
a=++count
cout<<"\n"<<" Object number = "<<a<< is created;
}
~sample()
//Destructor
{
cout<<"\nObject number = "<<a<<is destroyed;
}
};
int sample::count;
void main()
{ clrscr();
{
sample ob1;
//Created First Destructed Last
sample ob2;
//Created Second Destructed Last Second
sample ob3;
//Created Last Destructed First
}
//As scope is finishing so Destructors would be called
getch();
}

Overloaded constructors (or) multiple constructors in a class :

It is possible to have more than one constructor function with in the same class
by varying the argument list. This concept allows overloading the constructor
function. The following is an example
class sample
{ int m,n;
public:
sample ( ) // constructor -1
{
m=n=0;
}
sample (int i)// constructor - 2
{
m=n=i;
}
sample (int x, int y) // constructor - 3
{
m=x; n=y: }
};
Thus the following declaration statements causes the appropriate constructors
sample i; // calls constructor-1
sample i(10);
//calls constructor-2
sample i(10,20); // calls constructor -3
Constructors with default arguments:It is possible to define constructors with default arguments.
constructor complex can be defined as follows
complex (float real, float imag=0);

For ex. The

The default value of the argument imag is zero


Then the following statements, complex C(5.0); Assigns the value 5.0 to the real
variable and 0.0 to imag by default however the statement/ complex C(2.0,3.0);
assigns 2.0 to real and 3.0 to imag. Here the actual parameter 3.0 overrides the
default value (0.0)
Copy constructor:- A copy constructor is a special constructor in the C++
programming language used to create a new object as a copy of an existing
object. This constructor takes a single argument: a reference to the object to be
copied.
Normally the compiler automatically creates a copy constructor for each class
(known as an implicit copy constructor) but for special cases the programmer
creates the copy constructor, known as an explicit copy constructor. In such
cases, the compiler doesn't create one
There are four instances when a copy constructor is called:
1.
2.
3.
4.

When an object is returned by value


When an object is passed (into a function) by value as an argument
When an object is constructed based on other object (pf same class)
When compiler generates a temporary object (as in 1 and 2 above; as in
explicit casting, etc...)

Constructors of a class can be invoked by using existing objects of the class.


Syntax :- obect . class-name :: constructor-function-call ;
#include <iostream.h>
#include<conio.h>
class code
{ int d;
public:
code()
{cout<<"\ndefault constructor";
} // default constructor
code(int a) //constructor -2
{ d=a;
cout<<"\nparameterized contrctr";
}
code(code &x)//copy constructor
{ d=x.d;
cout<<"\ncopy cntrctr";
}
void display( )
{ cout<<"\nd="<<d<<endl;
}
};
void main( )
{
clrscr();
code A(100); //calls constructor - 2
code B(A);
//calls copy constructor
code C=A;
//calls copy constructor
code D;
//calls no argument constructor
D=A;// It is assignment not initialization hence no copy const. will be called
A.display ( );
B.display ( );
C.display ( );
D.display ( ) ;
getch();
}
Operator Overloading :1

Its a type of Polymorphism, where we can give additional meaning or


implementation to existing operators.
2. But the usage of Overloaded Operators should follow the usual rules laid
down by the compiler.

3.

Operator overloading is accomplished by means of special kind of function.


Operator overloading can be carried out by means of either member function
or friend function.

Syntax: return_type operator operator t o be overloaded( parameters);


Eg: void operator ++( ) // same as void increment();
/*4.
When using Type-Casting operators the following points need to be
remembered :a. It can Not be declared as Friend, so it has to be a member function.
b. No return-type not even void.
c. No input-arguments not even void. */
Rules for overloading operators: Only those operators that are predefined in the c++ compiler can be
overloaded. New operators cannot be created such as ( $ ,# , @).
Overloaded operator can not take default arguments.
We cant change the basic meaning of an operator, i.e., we cant
redefine the + to subtract one value from the other value.
We cannot overload any preprocessor symbol such as #.
We can not change the precedence or grouping of an operator nor we
can change the no of arguments it expects.
Unary operators overloaded by means of a member function take no
arguments and return no values. But unary operators overloaded by
means of a friend functions take one reference argument.
Binary operators overloaded through a member functions take one
argument and those, which are over loaded through a friend function,
take 2 arguments.
Overloaded operators follow the syntax rules of the original operators.
They cant be overridden
Binary arithmetic operators such as +, -, *, / must explicitly return a
value.
There are some operators that cant be overloaded (::, *, . , ?:, sizeof().
Using friend functions to overload >> and << operators
The following is an example program of overloading relational operator == to
compare the 2 given complex Nos.
OPERATOR
MEANING
Sizeof ( )
size of operator
.
Membership operator
.*
Pointer to member operator
::
scope resolution operator
?:
Ternary (or)conditional operator
it is possible to overload operators by using special member function operator
or a friend function calling operator member function.

The general form of overloaded operator member function is as follows


return type class name : : operator op(argument list)
The assignment operator has some additional restriction. It can be overloaded
as a non-static member function, not as friend function. It is the only operator
that can not be inherited. A derive class can not use a base class assignment
operator.
Operators that cannot be overloaded as friend.
1.
= operator(assignment operator)
2.
( ) operator (function call operator)
3.
[ ] operator (subscript operator)
4.
operator (arrow operator)
Ex: class sample
{ int x;
sample()
{ x=10; }
void operator +(int I )
void add( int I)
{ x=x+I;
}
void show( )
{ cout<<x;
}
void main()
{
sample obj;
obj.add(20) //obj+10;
obj.show();
getch();
}
output: 30.
Generate fibonacci series by overloading
(i)
prefix increment operator
(ii) postfix increment operator
1)SOURCE CODE ::
#include<iostream.h>
#include<conio.h>
#include<stdio.h>
#include<string.h>
class fib
{
int a,b,c;

public:
fib()
{
a=0;
b=1;
c=a+b;
}
void operator ++()
{
cout<<"\n\n"<<c;
a=b;
b=c;
c=a+b;
}
};
void main()
{
clrscr();
fib obj,obj1;
int i,n;
cout<<"\n\n Enter the no. of term's upto which series is to be displayed : ";
cin>>n;
cout<<0<<"\n\n"<<1;
for(i=0;i<n-2;i++)
{
++obj;
}
getch();
}
Write an OOP program to overload = = operator to compare two strings.
#include<iostream.h>
#include<conio.h>
#include<stdio.h>
#include<string.h>
class string
{
char s1[20];
public:
void get()
{ cout<<"\n\n Enter any string : ";
gets(s1);
}
int operator ==(string x)
{

int comp;
comp=strcmp(s1,x.s1);
if(comp==0)
return(1);
else
return(0);
}
};
void main()
{
string obj,obj1;
clrscr();
obj.get();
obj1.get();
if(obj==obj1)
{
cout<<"\n\n String's are equal ";
}
else
{
cout<<"\n\n String's are unequal ";
}
getch();
}
Overload the binary operator + using friend function to add two objects.
#include<conio.h>
#include<iostream.h>
class fib
{ int c;
public:
void get()
{ cin>>c;
}
friend fib operator +(fib &,fib &);
void show()
{ cout<<"\nc="<<c;
}
};
fib operator +(fib &x,fib &y)
{ fib z ;
z.c=x.c+y.c;
return(z);
}
void main()

{
clrscr();
fib f1,f2,f3;
f1.get();
f2.get();
f3=f1+f2;
f1.show();
f2.show();
f3.show();
getch();
}
Write an OOP program to overload = operator to copy the contents of one string
object to another string object.
SOURCE CODE ::
#include<iostream.h>
#include<conio.h>
#include<stdio.h>
#include<string.h>
class string
{
char s1[20];
public:
void get()
{
cout<<"\n\n Enter any string : ";
gets(s1);
}
void show()
{
cout<<"\n\n The copied String is : ";
puts(s1);
cout<<"\n\n";
}
void operator =(string x)
{
strcpy(s1,x.s1);
}
};
void main()
{
string obj,obj1;
clrscr();
obj.get();

obj1.get();
obj=obj1;
obj.show();
getch();
}
OUTPUT ::
Enter any string : HAPPY
Enter any string : BIRTHDAY
The copied String is : BIRTHDAY
Write an OOP program to overload < (less than) operator to find which of the
two string object is greater and
show the greater string object.
SOURCE CODE ::
#include<iostream.h>
#include<conio.h>
#include<stdio.h>
#include<string.h>
class string
{
char s1[20];
public:
void get()
{
cout<<"\n\n Enter any string : ";
gets(s1);
}
void show()
{
cout<<"\n\n Greater String is : ";
puts(s1);
cout<<"\n\n";
}
int operator <(string x)
{
int l1=strlen(s1);
int l2=strlen(x.s1);
if(l1>l2)
return(1);
else
return(0);
}
};
void main()

{
string obj,obj1;
clrscr();
obj.get();
obj1.get();
if(obj<obj1)
{
obj.show();
}
else
{
obj1.show();
}
getch();
}
OUTPUT ::
Enter any string : FOURTH
Enter any string : SEMESTER
Greater String is : SEMESTER

Das könnte Ihnen auch gefallen