Unit Ii
Unit Ii
DEPARTMENT OF BCA
Functions in C++:
Dividing a program into functions is one of the major principles of top-down
structured programming.
Advantages:
Reduce the size of the program
Reusability of code.
Syntax:
Void main ()
{
Declaration;
Statements:
Return (0);
}
Main()
{
message(); calling function
cout<<”hai”;
}
message()
{
cout<<”hello”; called fucntion
}
Actual parameters:
It is defined in calling function and they have actual values to be passed to the called
function.
Formal parameters:
It is defined in called function and they receive values of actual parameters when
function is invoked.
Function prototype:
The prototype describes the function interface to the compiler by giving details such
as
The number and type of arguments and
The type of return values
Function prototype is a declaration statement in the calling program and is of the following
form;
1
type function-name(argument-list);
The argument-list contains the types and names of arguments that must be passed to the
function.
Ex: float volume(int x, float y, float z);
Function prototype describes the function interface
Function definition:
A function definition has a name, a parenthesis pair containing zero or more
parameters and a function body. Any parameter not declared is taken to be int by default.
Syntax: function type function-name (data type argument1, data type
argument2…..)
{
Body of function
---------
---------
Return something
}
Ex:
Float volume(int a, float b, float c)
{
float v=a*b*c;
….}
Call by value:
Called function creates new variables to store the value of arguments passed to it.
It copies the value of actual parameters into the formal parameters.
Thus the function creates its own copies of arguments and then uses them.
Void swap(int,int);
Void main()
{
int a,b;
cin>>a>>b;
cout<<”before swap”;
swap(a,b);
cout<<a<<b;
}
void swap (int a1, , int b1 );
{
int temp;
temp= a1;
a1=b1;
b1=temp;
cout<<a<<b
}
2
Call By Reference:
Call by reference is a method in which the address of each argument is passed to the
function. By this method, the changes made to the parameters of the function will affect the
variables in the calling function.
Ex
// call by reference
#include<iostream.h>
void swap (int *x, int *y );
{
int temp;
temp= *x;
x=*y;
*y=temp;
}
void main ( )
{
int x = 10,= 20
swap (&x, &y);
cout << x <<y;
}
Return By Reference:
Return Statement:
The keyword return is used to terminate function and return a value to its caller. It also
be used to exit a function without returning any value. It is used in anywhere within function
body.
Syntax: return;
return(expression);
3
Ex: int sum(int x,int y)
{
return(x+y); }
float maximum(float b,float a)
{
if(a>b)
return(a);
else
return(b);
}
Inline Function:
An inline function is a function that is expanded inline when it is invoked. The
compiler replaces the function called with the corresponding function code.
Syntax:
inline function header.
{
function body;
}
Ex:
Inline float convert_ feet(int x)
{
return x*12;
}
void main()
{
int inch=45;
cout<<convert-feet(inches);
}
Default Arguments:
C++ allows us to call a function without specifying all its arguments. In such cases the
function assigns a default value to the parameter, which does not have a matching argument
in the function call. Default values are specified when the function is declared.
4
Ex:
int sum (int a, int b)
x = sum (10, 20);
passes the value of 10 to a and 20 to b.
Advantages
Default argument helps to add new parameters to the existing functions
Default argument can be used to combine similar functions into one
Constant Arguments:
An argument to function can be declared as constant
Eg: int strlen(const char *p);
int length ( const , string&s);
The qualifier constant tells the compiler that the function should not modify the argument.
The compiler will generate an error when this condition is violated.
Function overloading:
Overloading refers to the use of the same thing for different purpose. This means that we
can use the same function name to create functions that perform a variety of different
tasks.
Function overloading:
We can design a family of function with one function but with different argument lists.
The function would perform different operations depending on the argument list in the
function call. The correct function to be invoked is determined by checking the number and
type of the arguments but not on the function type.
//Declaration
int add(int a,int b);
int add(int a,int b,int c);
double add(double x,double y);
double add(int p,double q);
double add(double p,int q);
//function call
cout << add(5,10);
cout<<add(15,10.0);
cout<<and(12.5,7.5);
cout<<add(5,10,15);
cout <<add(add(0.75,5);
5
A function call first matches the prototype having the same number and type of argument
and then calls the appropriate function for execution .
Ex:
#include<iostream.h>
//declaration
int volume(int);
double volume(double,int);
long volume(long ,int ,int);
int main( )
{
cout << volume(10) << “\n”;
cout<<volume(2.5,8) << “\n”;
cout << volume(100,75,15) << “\n”;
return 0 ;
}
// function definition
int volume(int s) //cube
{
return(s*s*s);
}
double volume(double r,int h) //cylinder
{
return(3.14 * r * r * h);
}
long volume(long l,int b,int h) //rectangular
{
return(l*b*h);
}
Friend Function:
Virtual Functions:
6
A virtual function is one that does not really exists but it appears real in some parts of
program.
Syntax:
Class class_name
{ private:
members;
public :
virtual return_type function_name();
};
Ex:
Class student
{ private:
int rollno;
float avg;
public:
virtual void getdata();
virtual void display();
};
When using the same function name in both the database and derived classes, the
function in base class is declared as virtual using the key board virtual preceding its normal
declaration.
When a function is made virtual, C++ determines which function to use at run time based
on the type of object pointed to by the base pointer, rather than the type of the pointer. Thus,
by making the base pointer to different objects we can execute different version of the virtual
function.
7
While a base pointer can point to any type of the derived object, the reverse is
not true.(i.e) we cannot use a pointer to a derived class to access an object of the
base type.
When a base pointer points to a derived class, incrementing or decrementing it
will not make it to point to the next object of the derived class.
If a virtual function is defined in the base class, it need not be necessarily
redefined in the derived class. In such cases, calls will invoke the base function.
It is a function declared in a database class that has no definition relative to the base
class.
In such a cases, the compiler requires each derived class to either define the function
or redeclare it as a pure virtual function.
8
Class definition
Class function declarations
The class declaration describes the type and scope of its members. The class function
definitions describe how the class functions are implemented.
The class declaration is similar to a struct declaration. The body of a class is enclosed
within braces and terminated by a semicolon. The class body contains the declaration of
variables and functions. These functions and variables are collectively called members. They
are usually grouped under two sections.
(1) Private
(2) Public.
The keywords private and public are known as visibility labels. The members have
been declared as private can be accessed only from within the class. The public
members can be accessed outside the class.
The data hiding is the key features of object-oriented programming. The use of
keyword private is optional. By default, the members of a class are private.
The variables declared inside the class are known as data members and the functions
are known as member functions. Only the member functions can have access to the
private data members and private functions.
However, the public members can be accessed fro outside of the class. The binding of
data and functions together into a single class type, variable is referred to as
encapsulation
Example:
Class item
{
int no;
float cost;
public:
void get data(int a,int b)
void put data(void);
};
9
Object of A Class:
A class is a user defined data type, while an object is an instance of class template. A class provides a
template, which defines the member function and variables that are required for object of the class type.
Once a class has been created, we can create any number of objects belonging to that class. We can also
declare more than one object in one statement.
Ex: item x; // memory for x is
created
item x,y,z;
for example:
class item
{
……….
……… } x,y,z;
Accessing class members:
The private data of a class can be accessed only through the member functions. The object
can access a variable declared as public directly.
Syntax:
object-name. Function-name (actual-arguments);
Ex: x.getdata (100,75.5);
C++ program with class:
Example:
#include<iostream>
class item
{
private:
int number;
float cost;
public:
void getdata (int a, float b); //declaration
void putdata(void); //declaration
void item :: putdata (void)
{
cout << “Number:” <<number <<endl;
cout<< “Cost :” << cost << endl;
} };
void item :: getdata (int a , float b)
{ number = a;
cost = b;
}
Int Main()
{
Item x;
Cout<<”object x”<<”\n”;
x.getdata(100,299.95);
x.putdata();
item y;
cout<<”object y”<<”\n”;
y.getdata(200,175.50);
g.putdata();
}
10
Defining member function:
Member functions can be defined in two places:
Outside the class definition
Inside the class definition
Syntax:
return-type class-name :: function-name (argument declaration)
{ function body
}
The membership label class-name :: tells the compiler that the function name belongs
to the class class-name. That is, the scope of the function is restricted to the class-name
specified in the header line.
The symbol :: is called the scope resolution operator.
Example:
Void item::getdata(int a, float b)
{
Number = a;
Cost = b;
}
Void item :: put data(void)
{
Cout<<”number”<<number<<”\n”;
Cout<<”cost:”<<cost<<”\n”;
}
Syntax:
return type function name(argument decl
aration)
{ function body;
}
11
Example:
class item
private:
Int number;
float cost;
public:
void get data (int a, float b); //declaration
12
Nesting Of Member Function:
A number function can be called by using its name inside another member function of the
same class. This is known as nesting of member functions
public:
void update();
};
void sample: :update()
{
read();
}
13
An array is a user data type whose member is homogeneous and stored in contiguous
memory locations. The arrays can be used as member variable in a class.
Example:
class array
{ int a [size];
public:
void setval (void);
void display (void);
};
The array variable a [] declared as a private member of the class array can be used in
the member function like any other variable. In the above class definition the member
function setval( ) sets the values of elements of the array a [ ] and display( ) function
displays the values. Similarly we may use other member function to perform any other
operation on the array values.
14
Static Data Members:
Characteristics:
It is declared within the class, but its lifetime is the entire program.
It is initialized to zero when the first object of its class is created. No other
initialization permitted.
Only one copy of that member is created for the entire class and is shared by all the
objects that class, matter how many objects are created.
It is visible only
Class item Int item::count
{ Int main()
static int count; {
int num; item a,b,c;
public: a.getcount();
void getdata(int a) b.getcount();
{ c.getcount();
number=a; a.getdata(100);
count++; b.getdata(200);
} c.getdata(300);
void getcount(void) cout<<”after reading data”;
{ a.getcount()
cout<<”Count”; b.getcount();
cout<<count; c.getcount();
} return 0;
}; }
.
Static member functions:
A member function that is declared as static has the following properties:
A static member function can have access to only other static members declared
in the same class.
A static member function can be called using the class name [instead of its
objects].
class-name::function-name;]
Arrays Of Objects:
An array can be of any data type including struct. Similarly we can also have arrays of
variables that are of the type class. Such variables are called arrays of objects.
15
Ex:
class emp
{ char name [30]
float age;
public:
void getdata (void);
void putdata (void);
};
The identifier emp is a user-defined data type & can be used to create objects that
related to different categories of the employees.
Object may be used as a function argument. This can be done in two ways
1. A copy of the entire object is passed to the function.
2. Only the address of the object is transferred to the function.
The first method is called pass-by-value. Since a copy of the object is passed to the
function, any changes made to the object inside the function do not affect the object
used to call the function.
The second method is called pass-by-reference. When an address of the object is
passed, the called function works directly on the actual object used in the call. This
means that any changes made to the object inside the function will reflect in the actual
object.
The pass-by-reference method is more efficient since it requires passing only the
address of the object and not the entire object.
16
Friendly functions:
A friend is a function that is not a member of a class but has access to the private
members of the class. Normally private members are hidden from all parts of the program
outside the class and accessing them requires a call to public member function. To make an
outside function friendly to a class , we have to simply declare this function as a friend of the
class as shown below:
Class ABC
{ --------
--------
public:
--------
--------
friend void xyz(void) // declaration
};
Characteristics:
It is not in the scope of the class to which it has been declared as friend
It cannot be called using the object of the class
It can be invoked without the help of any object
It cannot access the member names directly
It has can be declared either private or the private part of a class
It has objects as arguments
It has often used in operator overloading
Example:
17
int a; return float(s.a+.s.b)/2.0;
int b; }
public: void main()
void setvalue() {
{a=25; sample x;
b=40; x.setvalue();
} cout<<”mean value=”<<mean(x)<<”\
friend float mean(sample s); n”;
}; return 0;
}
Returning object:
A function cannot only receive objects as arguments but also can return them .In the
below example we can create object and how object is return to another function is shown
below
Example:
#include<iostream.h> void complex :: show ( complex c)
Class complex {
{ cout<< c.x<<”+j”<<c.y<<”\n”;
float x; }
float y; int main()
public: {
void input ( float real, float imag) complex A,B,C;
{ A. input(3.1,5.65);
x= real; B.input( 2.1,1.2);
y= imag; C= sum (A,B); ///C=A+B
} cout<< “ A= “; A. show()
friend complex sum( complex, complex); cout<< “ B= “; B.show()
void show ( complex); cout<< “ C= “; C.show()
}; return 0;
complex sum ( complex c1, complex c2) }
{ output:
complex c3; A=3.1+j5.65
c3.x= c1.x+c2.x; B=2.75+j1.2
c3.y = c1.y+c2.y C=5.85+j6.85
return (c3) ;
}
18
If a member function does not alter any data in the class, then we may declare it as
const member function.
Eg: Void mul( int,int) const;
Double get balance() const;
The qualifier const is appended to the function prototypes( in declaration and
definition).
The compiler will generate an error message if such functions try to alter the data
values.
Pointers to members
It is possible to take the address of a member of a class can be assigned it to a pointer.
The address of a member can be obtained by applying the operator ‘&’ to a fully qualified
class member name. The class member pointer can be declared using the operator ::* with
the class name
Ex: Class A
{
Private:
Int m;
Public:
Void show();
};
Local class:
Classes can be defined and used inside a function or a block. Such classes are called as
local classes.
Example:
Void test(int a) // function
{
………
………
class student // local class
{
……..
……. // class definition
};
…….
Student s1(a); // create student object
use student object
Local classes can use global variables and static variables declared inside the function
cannot use automatic local variable.
The global variable should be used with the scope operator(::)
There are some restrictions in constructing local classes. They cannot have static data
members and Member functions must be defined inside the local classes.
19
Enclosing function cannot access the private members of a local class. But it can done
by declaring the enclosing function as a friend
There is no return type specified. A constructor many contain a return statement without
an argument about any attempt to return any type of value from a constructor is an error.
The name of the constructor function is the same as name of the class.
An initialization list may follow the name & argument of the constructor. The list is a
comma, separated list of class member with associated initial values. The list is separated
from the argument list by a single colon.
20
Parameterized Constructor
C++ permits us to achieve this objective by passing argument to the constructor function
when the objects C++ are created. The constructor that can take argument are called
parameterized constructor.
The constructor integer( ) may be modified to take argument as shown below
class integer
{
int m.n;
public:
integer(int m, int y) //parameterized
constructor
statement;
};
integer :: integer(int x , int y)
{
m=x;
x=y;
}
We must pass the initial values as argument to the constructor function when an object is
declared. This can be done in 2 ways.
1.By calling constructor explicitly
2.By calling the constructor implicitly
Explicit constructor:
integer int1=integer(0,100)
This method creates an integer object in it and passes the values 0 and 100 to it
Implicit constructor
class integer:
integer int1(0,100)
{
In this method,
int sometimes
m,n; called the shorthand method is used very often
public:
integer ( ) //constructor 1
{
m=0;
n=0;
}
integer (int a, int b) // constructor 2
Program For Multiple
{ Constructor:
m=a;
n=b;
}
integer (integer & i) // constructor 3
{
m=i.m;
n=i.n;
}
21
};
The first receives no argument. The 2 nd receives two integer arguments & the 3 rd
receives one integer object as an argument.
The default value of the argument imag is zero. Then, the statement complex c(5.0) .
Assigns the value 5.0 to the real 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 respectively.
22
Copy constructor is used to declare and initialize an object from another object.
It takes a reference to an object of the same class as itself as an argument.
Every class at least 2 constructors there are identified by their unique declaration.
Copy initialization:
The process of initializing through a copy constructor is known as copy initialization.
A copy constructor takes a reference to an object of the same class as itself as an
argument. Consider a simple example of constructing and using a copy constructor
Dynamic constructor:
The constructor can also be used to allocate memory while creating object. This will
enable the system to allocate the right amount of memory for each object when the objects
are not of the same size, thus resulting in the saving of memory. Allocation of memory at the
Const objects:
We may create and use constant objects using const keywords before object declaration.
Example:
Any attempt to modify the values of m and n will generate compile time error. A
constant object can call only const member function. Const member is a function
23
prototype or function definition where the keyword const appears after the functions
signature.
Whenever const objects try to invoke non-const member functions, the compiler
generates errors.
Destructors:
A destructor like a constructor has the same name as that of the class but is prefixed by
the tilde (~) symbol. It is only invoke when the object is destroyed. Add a destructor can’t
take arguments a specify a return values.
Syntax:
~matrix ( );
A Destructor never takes any arguments not does return any value. Whenever new is
used to allocate memory in the constructor we should use delete to free that memory.
Example:
matrix :: matrix ( )
{ for (i=0; i <n; i++)
delete p [i];
delete#include<iostream.h>
p;
} Int count =0;
Class alpha
{
Public:
Alpha()
{
Count++;
Cout<<”\n No.of object created “ <<count;
}
~alpha()
{
Cout<<”\n No.of object destroyed”<<count;
Count--;
}
}; Int main()
{ Cout<<”\n\n Enter main\n”;
Alpha A1,A2,A3,A4;
{
Cout<<”\n\nEnter block1\n”;
Alpha A5;
}{
Cout<<”\n\nEnter Block2\n”;
Alpha A6;
}Cout<<”\n\nRe-enter main\n”;
Return 0; 24
}
25