Beruflich Dokumente
Kultur Dokumente
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
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
Global data
M1
Module 2
F1
F2
M3
1.
2.
3.
4.
5.
6.
Data
Function
Data
Communication
Function
Function
Data
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.
Global Data
Function-1
Function-2
Data
Data
Functions
Functions
Communication
Local Data
Local Data
Object C
Functions
Data
9
10
11
12
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.
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
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.
Bird
Attributes:
Feathers
Lay eggs
Flying Bird
Attributes:
Parrot
Attributes:
..
..
Nonflying Bird
Attributes:
..
.
Robin
Attributes:
..
Panguin
Attributes:
..
Kiwi
Attributes:
..
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.
}
// 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.
Array
Pointer
Function
void
Integral type
int
Void: -
Derived
Data type
char
Floating type
float
double
1)
2)
3)
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
(iv)
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
break;
case value2:
program statement
break;
case valuen:
program statement
break;
default:
program statement
break;
}
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
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
name[1] = E
name[2] = N
name[3] = U
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
variable.
No extra space is required. Only a
or assignment
accessed
4. Used while implementing Call By
Used
Address
5. Common Syntax :-
Reference
Common Syntax :-
while
implementing
Call
By
Declaration :-
Declaration :-
Acquiring address :-
Manipulating data :-
variable .
reference = value ;
Manipulating data :-
variable.
Example :-
int a = 10 ;
int a = 10;
int *p ;
int &b = a;
p = &a;
b=20;
*p = 20;
.
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 ).
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);
}
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.
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.
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
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 .
The Public members of a Class get Inherited completely to the Child Classes.
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.
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.
}
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
Code
code
code
t1
t2
t3
3
showcode()
count
showcount()
setcode()
}
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 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);
3.
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