You are on page 1of 35

Introduction to Programming

Lecture 25
Introduction to C++
language
In Coming Lectures

– C++ Features
– Classes
– Object
Today’s Lecture
 Default Function Arguments
 Inline Functions

 Classes
Rules for Structured
Programming
 Do Modular programming
– Write small function
– Every function should perform
a specific well defined task
 Function should obey single entry
single exit rule
Liberally Comment
the code
Object Oriented
Language
Early 1980's
Bjarne Stroustrup
at Bell Labs
 C with Classes
 C++

 Java
Default Function
Arguments
power ( x , n ) ;
void f ( int i , double x ) ;
void f ( int i =1 , double x = 10.5 )
{
--
}
Example 1
void f ( int i = 1 , double x = 10.5 )
{
cout<<“i = ”<<i;
cout<<“ x = “<< x<<endl;
}
Example 1
main ( )
{ Output
f(); i = 1 x = 10.5
f(2); i = 2 x = 10.5
f ( 2 , 12 ) ; i = 2 x = 12
}
void f ( double x=10.5 , int i ) ;
The declaration of
variables inside the code
while ( condition )
{
// body of the while loop
}
{
int i ;
---
}
Scope of Variable
When you declare a
variable inside the block
then the variable exists in
that block.
Example 2
for ( int i = 0 ; i < 3 ; i++ )
{
int temp = 22 ;
cout << "\n i = " << i << "temp = " << temp ;
}
cout << "i = " << i ;
Inline
functions
inline
Example 2
#define SQUARE ( X ) X * X
main ( )
{
int i = 5 , j = 10 , k ;
:
k = iSQUARE
+ j * i +( ji ;+ j ) ;
}
Example 3
#define SQUARE ( X ) ( X ) * ( X )
main ( )
{
int i = 5 , j = 10 , k ;
( i + j ) *( (i i++j j) ); ;
k = SQUARE
}
Example 3
#define MAX ( A , B ) ( ( A ) > ( B ) ? ( A ) : ( B ) )
inline f ( int a, int b )
{
if ( a > b )
return a ;
return b ;
}
void main ( )
{
int i , x , y ;
x = 23 ; y = 45 ;
i = MAX ( x++ , y++ ) ; // Side - effect : larger value incremented twice
cout << "x = " << x << " y = " << y << '\n' ;
x = 23 ; y = 45 ;
i = f ( x++ , y++ ) ; // Works as expected
cout << "x = " << x << " y = " << y << '\n' ;
}
Function
Overloading
Operator
Overloading
Overloading
Using the same name to
perform multiple tasks or
different task depending on
the situation
double Intsquareroot ( int i ) ;
double Doublesquareroot ( double x ) ;
Example 4
int squareroot ( int i )
{
// body of the function
}

double squareroot ( double x )


{
// body of the function
}
Example 4
main ( )
{
double i , x ;
int j = 5 , k ;
i = squareroot ( 10.5 ) ;
cout << i << endl ;
k = squareroot ( j ) ;
cout << k << endl ;
}
Example
F ( int a , int b ) ;
F ( int a , int b , int c ) ;

main ( )
{
-----------
F(1,2); // F ( int a , int b ) ; is called
F ( 1 , 2 , 3 ) ; // F ( int a , int b , int c ) ; is called
-----------
}
int f ( int a ) ;
double f ( int a ) ;
Name Mangling

You might also like