C Unit-2
C Unit-2
FUNCTION IN C++ :
2.1 The main( ) Function ;
main() function is the entry point of any C++ program. It is the point at which execution of program is
started. When a C++ program is executed, the execution control goes directly to the main() function.
Every C++ program have a main() function.
Syntax
void main()
{
............
............
}
In above syntax;
void: is a keyword in C++ language, void means nothing, whenever we use void as a function return
type then that function nothing return. here main() function no return any value.
In place of void we can also use int return type of main() function, at that time main() return integer
type value.
main: is a name of function which is predefined function in C++ library.
#include<stdio.h>
void main()
}
Output
This is main function
2.2.FUNCTION PROTOTYPING
Before a function can be used (called) anywhere in a C++ program, it must be declared (a function
prototype) and defined (a function definition).
A function prototype is a declaration of the function that tells the program about the type of value returned
by the function and the number and type of arguments.
Function prototyping is one very useful feature of C++ functions. A function 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.
The prototype declaration looks just like a function definition, except that it has no body, i.e., its code is
missing. This is the first time you knew the difference between a declaration and a definition.
A declaration introduces a function name to the program, whereas a definition is a declaration that also
tells the program what the function is doing and how it is doing it.
return type
name of the function
argument list
Here,
Note: Each function prototype is followed by a semicolon. A function declaration can skip the argument
names, but a function definition cannot.
Use of void
The void data type specifies an empty set of values. As a result, the declaration of a function that does not
return a value looks like this:
One can ensure that a function cannot be used in an assignment statement by declaring the function's return
type to be void.
A function that does not require any parameters (i.e., it has an empty argument list) can be declared as
follows:
return_type function_name(void);
Note: If you don't include the type specifier for a function, it is assumed that the function will return
integer values. The type specifier is required to be provided for any functions that return values that are not
integers.
A function must be defined before it can be invoked. The function definition contains codes that specify
the function's work. That is, we define what the function will do in the program through the function
definition. The general form of the function definition is as follows:
The "return_type" specifies the type of value that the return statement of the function returns. It may be any
valid C++ data type. If no type is specified, the compiler assumes that the function returns an integer value.
The "function_name" is the name of the function. The "list of arguments" is a comma-separated list of a
function's variables. The "body of the function" contains the set of statements that define the work of the
function. For example,
The above code snippet from the "function definition" defines the function named "sum()." And based on
its definition, the function "sum()" takes two arguments and copies the values to the "x" and "y" variables,
whose addition result will be initialized to the "res" variable. And finally, using the "return statement," the
value of "res" will be returned to the calling function. For example:
#include<iostream.h>
int main()
{
int num1, num2, add;
cout<<"Enter two numbers: ";
cin>>num1>>num2;
cout<<"\nResult = "<<add;
cout<<endl;
return 0;
}
int sum(int x, int y) // function definition
{
int res;
res = x+y;
return res;
}
2.3 CALL BY REFEREN
The call by reference method of passing arguments to a function copies the reference of an argument into
the formal parameter. Inside the function, the reference is used to access the actual argument used in the call.
This means that changes made to the parameter affect the passed argument.
To pass the value by reference, argument reference is passed to the functions just like any other value.
// function declaration
void swap(int &x, int &y);
int main () {
// local variable declaration:
int a = 100;
int b = 200;
return 0;
}
When the above code is compiled and executed, it produces the following result −
Before swap, value of a :100
Before swap, value of b :200
After swap, value of a :200
After swap, value of b :100
2.5 RETURN BY REFERENCE
Pointers and References in C++ held close relation with one another. The major difference is that the
pointers can be operated on like adding values whereas references are just an alias for another variable.
Functions in C++ can return a reference as it’s returns a pointer.
When function returns a reference it means it returns a implicit pointer.
Return by reference is very different from Call by reference. Functions behaves a very
important role when variable or pointers are returned as reference.
Syntax:
dataType& functionName(parameters);
where,
dataType is the return type of the function,
and parameters are the passed arguments to it.
#include <iostream.h>
int& returnValue(int& x)
// Return reference
return x;
// Driver Code
int main()
int a = 20;
int& b = returnValue(a);
returnValue(a) = 13;
return 0;
Output:
x = 20 The address of x is 0x7fff3025711c
a = 20 The address of a is 0x7fff3025711c
b = 20 The address of b is 0x7fff3025711c
x = 20 The address of x is 0x7fff3025711c
a = 13 The address of a is 0x7fff3025711c
Explanation:
Since reference is nothing but an alias(synonym) of another variable, the address of a, b and x never
changes.
output:-
121.227898
1.257128
2.6 DEFAULT ARGUMENT:-
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 arguments in the function call. Default
values are specified when the function is declared. The compiler looks at the prototype to see how many
arguments a function uses and alerts the program for possible default values.
Example: float amount (float principle, int period ,float rate=0.15);
The default value is specified in a manner syntactically similar to a variable initialization .The above
prototype declares a default value of 0.15 to the argument rate. A subsequent function call like
value=amount(5000,7); //one argument missing
passes the value of 5000 to principle and 7 to period and then lets the function, use default value of
0.15 for rate.
The call:- value=amount(5000,5,0.12);
//no missing argument passes an explicite value of 0.12 rate.
One important point to note is that only the trailing arguments can have default values. That is, we must
add default from right to left .We cannot provide a default to a particular argument in the middle of an
argument list.
Example:- int mul(int i, int j=5,int k=10);//illegal int mul(int i=0,int j,int k=10);//illegal int mul(int i=5,int
j);//illegal
int mul(int i=2,int j=5,int k=10);//illegal
Default arguments are useful in situation whose some arguments always have the some value.
For example,bank interest may retain the same for all customers for a particular period of deposit.
Example:
#include<iostream.h>
main( )
{
float amount;
float value(float p,int n,float r=0.15);
void printline(char ch=’*’,int len=40);
printline( );
amount=value(5000.00,5);
cout<<”\n final value=”<<amount<<endl;
printline(‘=’);
}
//function definitions
float value (float p,int n, float r)
{
float si;
si=(p*n*r)/100;
return(si);
}
void printline (char ch,int len)
{
for(inti=l;i<=len;i++) cout<<ch<<endl;
}
output:-
* * * * * * * * * * * * * * * * final value=10056.71613
===============
Advantage of providing the default arguments are:
1. We can use default arguments to add new parameters to the existing functions.
2. Default argument s can be used to combine similar functions into one.
CONST ARGUMENT:-
In C++, an argument to a function can be declared as unit as const
as shown below.
int strlen(const char *p); int length(const string &s);
The qualifier const tells the compiler that the function should not modify the argument .the compiler will
generate an error when this condition is violated .This type of declaration is significant only when we pass
arguments by reference or pointers.
2.7 FUNCTION OVERLOADING:
Overloading refers to the use of the same thing for different purposes . C++ also permits overloading
functions . This means that we can use the same function name to creates functions that perform a variety
of different tasks. This is known as function polymorphism in oops.
Using the concepts of function overloading , a family of functions with one function name but with
different argument lists in the functions call .The correct function to be invoked is determined by checking
the number and type of the arguments but not on the function type.
A function call first matches the prototype having the same no and type of arguments and then calls the
appropriate function for execution.
The function selection invokes the following steps:-
a) The compiler first tries to find an exact match in which the types of actual
arguments are the same and use that function .
b) If an exact match is not found the compiler uses the integral promotions to the actual
arguments such as :
char to int float to double to find a match
c) When either of them fails ,the compiler tries to use the built in conversions to the actual
arguments and then uses the function whose match is unique . If the conversion is possible to
have multiple matches, then the compiler will give error message.
Example:
long square (long n); double square(double x);
A function call such as :- square(lO)
Will cause an error because int argument can be converted to either long or double .There by creating an
ambiguous situation as to which version of square( )should be used.
PROGRAM
#include<iostream.h>
int volume(double,int);
double volume( double , int );
double volume(longint ,int ,int);
main( )
{
cout<<volume(10)<<endl;
cout<<volume(10)<<endl; cout<<volume(10)<<endl;
}
int volume( ini s)
{
return (s*s*s); //cube
}
double volume( double r, int h)
{
return(3.1416*r*r*h); //cylinder
}
long volume (longint 1, int b, int h)
{
return(1*b*h); //cylinder
}
output:- 1000
157.2595
112500
2.8 CLASS:-
Class is a group of objects that share common properties and relationships .In C++, a class is a new data
type that contains member variables and member functions that operates on the variables. A class is
defined with the keyword class. It allows the data to be hidden, if necessary from external use. When we
defining a class, we are creating a new abstract data type that can be treated like any other built in data
type.
Generally a class specification has two parts:-
a) Class declaration
b) Class function definition
the class declaration describes the type and scope of its members. The class function definition describes
how the class functions are implemented.
Syntax:-
class class-name
{
private:
variable declarations;
function declaration ;
public:
variable declarations;
function declaration;
};
The members that have been declared as private can be accessed only
from with in the class. On the other hand , public members can be accessed from outside the class also. The
data hiding is the key feature of oops. The use of keywords 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
members mid the functions. Only the member functions can have access to the private data members and
private functions. However, the public members can be accessed from the outside the class. The binding of
data and functions together into a single class type variable is referred to as encapsulation.
class item
{
int member;
float cost;
public:
void getdata (int a ,float b);
void putdata (void);
};
The class item contains two data members and two function members, the data members are private by
default while both the functions are public by declaration. The function getdata() can be used to assign
values to the member variables member and cost, and putdata() for displaying their values . These
functions provide the only access to the data members from outside the class.
CREATING OBJECTS:
Once a class has been declared we can create variables of that
type by using the class name.
Example:
item x;
creates a variables x of type item. In C++, the class variables are known as objects. Therefore x is called an
object of type item.
item x, y ,z also possible. class item
{
}x ,y ,z;
would create the objects x ,y ,z of type item.
ACCESSING CLASS MEMBER:
The private data of a class can be accessed only through the member functions of that class. The main()
cannot contains statements that the access number and cost directly.
Syntax:
object name.function-name(actual arguments);
Example:-
x. getdata(100,75.5);
It assigns value 100 to number, and 75.5 to cost of the object x by implementing the getdata() function .
similarly the statement
x. putdata ( ); //would display the values of data members.
x. number = 100 is illegal .Although x is an object of the type item to which number belongs , the number
can be accessed only through a member function and not by the object directly.
Example:
class xyz
{
Int x;
Int y;
public:
int z;
};xyz p;
p. x =0; error . x is private
p, z=10; ok ,z is public
2.9 DEFINING MEMBER FUNCTION:
Member can be defined in two places
• Outside the class definition
• Inside the class function
OUTSIDE THE CLASS DEFlNAT1ON;
Member function that are declared inside a class have to be defined separately outside the class. Their
definition are very much like the normal functions.
An important difference between a member function and a normal
function is that a member function incorporates a membership. Identify label in the header. The ‘label’ tells
the compiler which class the function belongs to.
Syntax:
return type class-name::function-name(argument declaration )
{
function-body
}
The member ship label class-name :: tells the compiler that the function 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 scope resolution operator.
Example:
void item :: getdata (int a , float b )
{
number=a; cost=b;
}
void item :: putdata ( void)
{
cout<<”number=:”<<number<<endl; cout<<”cost=”<<cost<<endl;
}
The member function have some special characteristics that are often used in the program development.
• Several different classes can use the same function name. The "membership label" will
resolve their scope, member functions can access the private data of the class
A non member function can't do so.
A member function can call another member function directly, without using the dot
operator.
INSIDE THE CLASS DEF1NATION:
Another method of defining a member function is to replace the function declaration by the actual function
definition inside the class .
Example:
class item
{
int number; float cost;
pupuc:
blic:
void getdata (int a ,float b); void putdata(void)
{
cout<<number<<endl; cout<<cost<<endl;
}
};
PROGRAM WITH CLASS:
# include< iostream. h>
class item
{
int number; float cost;
public:
void getdata ( int a , float b); void putdala ( void)
{
cout<<“number:”<<number<<endl; cout<<”cost :”<<cost<<endl;
l}
};
void item :: getdata (int a , float b)
{
number=a; cost=b;
}
main ( )
{
item x;
cout<<”\nobjectx”<<endl;
x. getdata( 100,299.95);
x .putdata();
item y;
cout<<”\n object y”<<endl;
y. getdata(200,175.5);
y. putdata();
}
Output:
object x number 100
cost=299.950012
object -4 cost=175.5
Write a simple program using class in C++ to input subject mark and prints it.
class marks
{
private :
int ml,m2; public:
void getdata(); void displaydata();
};
void marks: :getdata()
{
cout<<”enter 1st subject mark:”; cin>>ml;
cout<<”enter 2nd subject mark:”; cin>>m2;
}
void marks: :displaydata()
{
cout<<”Ist subject mark:”<<ml<<endl ; cout<<”2nd subject mark:”<<m2;
}
void main()
{
clrscr(); marks x; x.getdata();
x.displaydata();
}
2.10 NESTING OF MEMBER FUNCTION;
A member function can be called by using its name inside another member function of the same class. This
is known as nesting of member functions.
#include <iostream.h> class set
{
int m,n; public:
void input(void); void display (void); void largest(void);
};
void set::input(void)
{
cout<<”input values of m and n:”; cin>>m>>n;
}
void set::display(void)
{
cout<<”largestvalue=”<<largest()<<”\n”;
}
void main()
{
set A;
A.input( );
A.display( );
}
output:
Input values of m and n: 30 17
largest value= 30
2.11 Private member functions:
A function declared inside the private access specifier of the class, is known as a private member function.
A private member function can be accessed through the only public member function of the same class.
Example:
For example, there is a class named “Student”, which has the following private data members and public
member functions:
Private Data members
read() – read() function is used here to read roll number and percentage of the
student.
print() – print() function is used to print roll number and percentage of the student
Here, TakeNumbersBegin () and TakeNumbersBeginFinish () are the private member functions which are
calling inside public member function in the same class
#include <iostream.h>
class Student
{
private:
int rNo;
float percentage;
void TakeNumbersBegin(void)
{
cout<<"Input start..."<<endl;
}
void TakeNumbersBeginFinish(void)
{
cout<<"Input end..."<<endl;
}
public:
//public member functions
void read(void)
{
//calling first member function
TakeNumbersBegin();
TakeNumbersBeginFinish();
}
void print(void)
{
cout<<endl;
cout<<"Roll Number: "<<rNo<<endl;
cout<<"Percentage: "<<percentage<<"%"<<endl;
}
};
//Main code
int main()
{
//declaring object of class student
Student object1;
return 0;
}
Output
Input started…
Enter roll number: 5
Enter percentage: 10
Input Finish…
Roll Number: 5
Percentage: 10
2,12 ARRAYS WITHIN CLASSES:
#include<iostream.h>
const int size=5;
class student
{
int roll_no;
int marks[size];
public:
void getdata ();
void tot_marks ();
};
void main()
student stu;
stu.getdata() ;
stu.tot_marks() ;
getch();
}
ARRAY OF OBJECTS:-
Like array of other user-defined data types, an array of type class can also be created.
The array of type class contains the objects of the class as its individual elements.
Thus, an array of a class type is also known as an array of objects.
An array of objects is declared in the same way as an array of any built-in data type.
Syntax:
Example:
#include <iostream.h>
class MyClass {
int x;
public:
void setX(int i)
{ x = i; }
int getX()
{ return x; }
};
void main()
{
MyClass obs[4];
int i;
void getdata() {
cout << "Enter roll number: "<<endl;
cin >> rollNo;
cout << "Enter name: "<<endl;
cin >> name;
cout << "Enter marks: "<<endl;
cin >> marks;
}
void putdata() {
cout<<"Roll Number = "<< rollNo <<endl;
cout<<"Name = "<< name <<endl;
cout<<"Marks = "<< marks <<endl;
cout<<endl;
}
};
int Student::objectCount = 0;
int main(void) {
Student s1;
s1.getdata();
s1.putdata();
Student s2;
s2.getdata();
s2.putdata();
Student s3;
s3.getdata();
s3.putdata();
cout << "Total objects created = " << Student::objectCount << endl;
return 0;
}
Output
The output of the above program is as follows −
Enter roll number: 1
Enter name: Mark
Enter marks: 78
Roll Number = 1
Name = Mark
Marks = 78
static member functions in C++ are the functions that can access only the static data members. These static
data members share a single copy of themselves with the different objects of the same class. A function can
be made static by using the keyword static before the function name while defining a class.
Syntax:
Example:
class scaler{
cout<<number<<"\n";
};
int scaler::number;
class scaler
{
static int number:
public:
static void get_no_of_topics()
{
cout << "The number of topics already assigned:"
<< number << endl;
}
};
int scaler::number=25;
int main()
{
scaler S; //object of class scaler
S.get_no_of_topics(); // object using '.' operator to access static member function
return 0;
}
Output:
4. Static member function in C++ can never be inline. This is to reduce heavy memory penalty as the
function call gets replaced by function code if declared inline. (Note: Inline functions are used for
writing smaller codes to speed up the program).
5. Static member functions cannot be declared as a virtual function. This is because virtual functions
in C++ are usually member functions of the base class and depend on the objects to invoke the
functions.
6. This pointer is not accessible by static member functions.
#include <iostream.h>
class Test{
public:
int a;
// This function will take object as arguments and return object
Test add(Test Ta, Test Tb)
{
Test Tc;
Tc.a = Ta.a + Tb.a;
// returning the object
return Tc;
}
};
int main()
{
Example T1, T2, T3;
// Values are initialized for both objects
T1.a = 50;
T2.a = 100;
T3.a = 0;
cout << "Initial Values \n";
cout << "Value of object 1: " << T1.a
<< ", \nobject 2: " << T2.a
<< ", \nobject 3: " << T3.a << "\n";
// Passing object as an argument to function add()
T3 = T3.add(T1, T2);
// Changed values after passing object as an argument
cout << "New values \n";
cout << "Value of object 1: " << T1.a
<< ", \nobject 2: " << T2.a
<< ", \nobject 3: " << T3.a
<< "\n";
return 0;
}
Output:
Initial Values
Value of object 1: 50,
object 2: 100,
object 3: 0
New values
Value of object 1: 50,
object 2: 100,
object 3: 150
The friend function is declared using the friend keyword inside the body of the class.
class className {
... .. ...
friend returnType functionName(arguments);
... .. ...
}
By using the keyword, the ‘friend’ compiler understands that the given function is a friend function.
In the above declaration, the keyword friend precedes the function. We can define the friend function
anywhere in the program like a normal C++ function. A class’s function definition does not use either the
keyword friend or scope resolution operator ::
We declare friend function inside the body of a class, whose private and protective data needs to be
accessed, starting with the keyword friend to access the data. We use them when we need to operate
between two different classes at the same time.
Friend functions of the class are granted permission to access private and protected members of the class
in C++. They are defined globally outside the class scope. Friend functions are not member functions of
the class.
A friend function in C++ is a function that is declared outside a class but is capable of accessing the private
and protected members of the class. There could be situations in programming wherein we want two
classes to share their members. These members may be data members, class functions or function
templates. In such cases, we make the desired function, a friend to both these classes which will allow
accessing private and protected data of members of the class.
Generally, non-member functions cannot access the private members of a particular class. Once declared as
a friend function, the function is able to access the private and the protected members of these classes.
The function is not in the ‘scope’ of the class to which it has been declared a friend.
Friend functionality is not restricted to only one class
Friend functions can be a member of a class or a function that is declared outside the scope of class.
It cannot be invoked using the object as it is not in the scope of that class.
We can invoke it like any normal function of the class.
Friend functions have objects as arguments.
It cannot access the member names directly and has to use dot membership operator and use an
object name with the member name.
We can declare it either in the ‘public’ or the ‘private’ part.
These are some of the friend functions in C++ characteristics
Implementing Friend Functions
We declare a friend class when we want to access the non-public data members of a particular class.
A Global function:
A ‘global friend function’ allows you to access all the private and protected members of the global class
declaration.
A simple example of a C++ friend function used to print the length of the box.
Length of box:10
int main ()
{
weight w1,w2 ,w3;
cout<<"Enter weight in kilograms and grams\n";
cout<<"\n Enter weight #1" ;
w3 = w1.sum_weight (w2);
w1.getdata();
cout<<" \n Enter weight #2" ;
w2.getdata();
w3.sum_weight(wl,w2);
cout<<"/n Weight #1 = ";
w1.putdata();
cout<<"Weight #2 = ";
w2.putdata();
cout<<"Total Weight = ";
w3.putdata();
return 0;
}
As the return type of function is weight (an object of class weight), a temporary object temp is created
within the function for holding return values. These values are accessed as temp kilogram and temp gram
by the function. When the control returns to main (), the object temp is assigned to the object w3 in main(
).
Pointers to members allow you to refer to nonstatic members of class objects. You cannot use a pointer to
member to point to a static class member because the address of a static member is not associated with any
particular object. To point to a static class member, you must use a normal pointer.
You can use pointers to member functions in the same manner as pointers to functions. You can compare
pointers to member functions, assign values to them, and use them to call member functions. Note that a
member function does not have the same type as a nonmember function that has the same number and type
of arguments and the same return type.
Pointers to members can be declared and used as shown in the following example:
#include <iostream>
class X {
public:
int a;
void f(int b) {
cout << "The value of b is "<< b << endl;
}
};
int main()
{
}
The output for this example is:
The value of a is 10
The value of b is 20