0% found this document useful (0 votes)
35 views

C Unit-2

The document discusses various aspects of functions in C++. It begins by explaining the main() function, which is the entry point of any C++ program. It then discusses function prototyping, which involves declaring a function before defining and calling it. This informs the compiler about the function signature. The document also covers function definitions, void return types, call by reference, return by reference, inline functions, and default arguments. Functions allow breaking down a problem into smaller, modular pieces of code that can be called to perform tasks.

Uploaded by

BHARATHI T
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
35 views

C Unit-2

The document discusses various aspects of functions in C++. It begins by explaining the main() function, which is the entry point of any C++ program. It then discusses function prototyping, which involves declaring a function before defining and calling it. This informs the compiler about the function signature. The document also covers function definitions, void return types, call by reference, return by reference, inline functions, and default arguments. Functions allow breaking down a problem into smaller, modular pieces of code that can be called to perform tasks.

Uploaded by

BHARATHI T
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 33

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.

Simple example of main()

#include<stdio.h>

void main()

cout<<"This is main function";

}
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.

Thus, the following are declarations or function prototypes:

int absval(int a);


int gcd(int n1, int n2);

A function prototype has the following parts:

 return type
 name of the function
 argument list

Look at the following function prototype:

int sum(int n1, int n2);

Here,

 return type: int


 name of the function: sum
 argument list: (int n1, int n2)

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:

void function_name(list of parameters);

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.

C++ function definition

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:

return_type function_name(list of parameters)


{
// body of the function
}

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,

int sum(int x, int y)


{
int res;
res = x+y;
return res;
}

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 sum(int x, int y); // function prototype

int main()
{
int num1, num2, add;
cout<<"Enter two numbers: ";
cin>>num1>>num2;

add = sum(num1, num2); // function call

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;

cout << "Before swap, value of a :" << a << endl;


cout << "Before swap, value of b :" << b << endl;

/* calling a function to swap the values using variable reference.*/


swap(a, b);

cout << "After swap, value of a :" << a << endl;


cout << "After swap, value of b :" << b << endl;

return 0;
}

// function definition to swap the values.


void swap(int &x, int &y)
{
int temp;
temp = x; /* save the value at address x */
x = y; /* put y into x */
y = temp; /* put x into y */
return;
}

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.

Below is the code to illustrate the Return by reference

// C++ program to illustrate return by reference

#include <iostream.h>

// Function to return as return by reference

int& returnValue(int& x)

cout << "x = " << x

<< " The address of x is "

<< &x << endl;

// Return reference

return x;

// Driver Code

int main()

int a = 20;
int& b = returnValue(a);

// Print a and its address

cout << "a = " << a

<< " The address of a is "

<< &a << endl;

// Print b and its address

cout << "b = " << b

<< " The address of b is "

<< &b << endl;

returnValue(a) = 13;

cout << "a = " << a

<< " The address of a is "

<< &a << endl;

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.

2.5 INLINE FUNCTION:


To eliminate the cost of calls to small functions C++ proposes a new feature called inline function. An
inline function is a function that is expanded inline when it is invoked .That is the compiler replaces the
function call with the corresponding function code.
The inline functions are defined as follows:-
inline function-header
{
function body;
}
Example: inline double cube (double a)
{
return(a*a*a);
}
The above inline function can be invoked by statements like c=cube(3.0);
d=cube(2.5+1.5);
remember that the inline keyword merely sends a request, not a command to the compliler. The compiler
may ignore this request if the function definition is too long or too complicated and compile the function as
a normal function.
Some of the situations where inline expansion may not work are:
1. For functions returning values if a loop, a switch or a go to exists.
2. for functions not returning values, if a return statement exists.
3. if functions contain static variables.
4. if inline functions are recursive,.
Example:
#include<iostream.h> #include<stdio.h>
inline float mul(float x, float y)
{
return(x*y);
}
inline double div(double p.double q)
{
return(p/q);
}
main( )
{ float a=12.345; float b=9.82;
cout<<mul(a,b)<<endl;
cout<<div (a,b)<<endl;
}

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);
};

int set::largest (void)


{
if(m>n)
return m;
else
return n;
}

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

 rNo is used to store the roll number of the student.


 perc is used to store the percentage of the student.

Public Member functions

 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;

//private member functions

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();

//read rNo and percentage


cout<<"Enter roll number: ";
cin>>rNo;
cout<<"Enter percentage: ";
cin>>percentage;

//calling second member function

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;

//reading and printing details of a student


object1.read();
object1.print();

return 0;
}
Output
Input started…
Enter roll number: 5
Enter percentage: 10
Input Finish…
Roll Number: 5
Percentage: 10
2,12 ARRAYS WITHIN CLASSES:

 Arrays can be declared as the members of a class.


 The arrays can be declared as private, public or protected members of the class.

A program to demonstrate the concept of arrays as class members

#include<iostream.h>
const int size=5;
class student
{
int roll_no;
int marks[size];
public:
void getdata ();
void tot_marks ();
};

void student :: getdata ()


{
cout<<"\nEnter roll no: ";
Cin>>roll_no;
for(int i=0; i<size; i++)
{
cout<<"Enter marks in subject"<<(i+1)<<": ";
cin>>marks[i] ;
}

void student :: tot_marks() //calculating total marks


{
int total=0;
for(int i=0; i<size; i++)
total+ = marks[i];
cout<<"\n\nTotal marks "<<total;
}

void main()
student stu;
stu.getdata() ;
stu.tot_marks() ;
getch();
}

Enter marks in subject 2 : 54


Enter marks in subject 3 : 68
Enter Output:
Enter roll no: 101
Enter marks in subject 1: 67
marks in subject 4 : 72
Enter marks in subject

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:

class_name array_name [size] ;

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;

for(i=0; i < 4; i++)


obs[i].setX(i);

for(i=0; i < 4; i++)


cout << "obs[" << i << "].getX(): " << obs[i].getX() << "\n";
getch();
}
Output:
obs[0].getX(): 0
obs[1].getX(): 1
obs[2].getX(): 2
obs[3].getX(): 3

2.13 STATIC DATA MEMBER:


Static data members are class members that are declared using the static keyword. There is only one copy
of the static data member in the class, even if there are many class objects. This is because all the objects
share the static data member. The static data member is always initialized to zero when the first class object
is created.
The syntax of the static data members is given as follows −
Static data_type data_member_name;
In the above syntax, static keyword is used. The data_type is the C++ data type such as int, float etc. The
data_member_name is the name provided to the data member.
A program that demonstrates the static data members in C++ is given as follows −
Example
#include <iostream.h>
#include<string.h>
class Student {
private:
int rollNo;
char name[10];
int marks;
public:
static int objectCount;
Student() {
objectCount++;
}

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

Enter roll number: 2


Enter name: Nancy
Enter marks: 55
Roll Number = 2
Name = Nancy
Marks = 55

Enter roll number: 3


Enter name: Susan
Enter marks: 90
Roll Number = 3
Name = Susan
Marks = 90
Total objects created = 3

A static member variable has certain special characteristics.


1) It is initialized to zero when the first object of its class is created. No other
initialization is permitted.
2) Only one copy of that member is created for the entire class and is shared by all
the objects of that class, no matter how many objects are created.
3) It is visible only with in the class but its life time is the entire program. Static
variables are normally used to maintain values common to the entire class. For
example a static data member can be used as a counter that records the
occurrence of all the objects.

2.14 STATIC MEMBER FUNCTIONS:-

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:

static return type function_name()

Example:

class scaler{

static int number;

static void get_no_of_topics() //static function declaration

cout<<number<<"\n";
};

int scaler::number;

Properties of Static Member Functions

The following are the properties of static member functions:

1. Static members can only be accessed by static member functions.


2. To invoke a static member function, the class name is used inplace of the object name using the
scope resolution operator. ie, to call a static member function in C++, say for eg;
get_no_of_topics(), we have to write scalar :: get_no_of_topics();
3. To access the static member function in C++ using an object, the dot operator is used. For eg:

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:

The number of topics already assigned: 25

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.

2.15 OBJECTS AS FUNCTION ARGUMENTS


Like any other data type, an object may be used as A function argument. This can come 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 change
made to the object inside the function do not effect 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 functions will reflect in the actual object .The pass by reference method is more efficient
since it requires to pass only the address of the object and not the entire object.

#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

2.16 FRIENDLY FUNCTIONS:-


A friend function in C++ is defined as a function that can access private, protected and public members of
a class.

The friend function is declared using the friend keyword inside the body of the class.

Friend Function Syntax:

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 ::

Friend function is called as function_name(class_name) and member function is called as class_name.


function_name.

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.

Characteristics of Friend Function

 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

Friend Functions can be implemented in two ways:

A method of another class:

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.

Code: #include <iostream.h>


class Box
{
private:
int length;
public:
Box (): length (0) {}
Friend int printLength (Box); //friend function
};
int printLength (Box b)
{
b. length +=10;
return b. length;
}
int main ()
{
Box b;
cout <<” Length of box:” <<printLength (b)<<endl;
return 0;
}
Output:

Length of box:10

2.17 RETURNING OBJECTS:


A function can also return objects either by value or by reference. When an object is returned by value from
a function, a temporary object is created within the function, which holds the return value. This value is
further assigned to another object in the calling function.
The syntax for defining a function that returns an object by value is
class_name function_name (parameter_list) {
// body of the function
}
Example: A program to demonstrate the concept of returning objects from a function
#include<iostream.h>
class weight {
int kilogram;
int gram;
public:
void getdata ();
void putdata ();
void sum_weight (weight,weight) ;
weight sum_weight (weight) ;
};

void weight :: getdata() {


cout<<"/nKilograms:";
cin>>kilogram;
cout<<"Grams:";
cin>>gram;
}

void weight :: putdata ()


{
cout <<kilogram<<" Kgs. and"<<gram<<" gros.\n";
}

weight weight :: sum_weight(weight w2)


{
weight temp;
temp.gram = gram + w2.gram;
temp.kilogram=temp.gram/1000;
temp.gram=temp.gram%1000;
temp.kilogram+=kilogram+w2.kilogram;
return(temp);
}

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(
).

2.18 POINTER TO MEMBERS;

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()
{

int X :: *ptiptr = &X::a; // declare pointer to data member

void (X::* ptfptr) (int) = &X::f; // declare a pointer to member function


X xobject; // create an object of class type X

xobject.*ptiptr = 10; // initialize data member


cout << "The value of a is " << xobject.*ptiptr << endl;

(xobject.*ptfptr) (20); // call member function

}
The output for this example is:
The value of a is 10
The value of b is 20

You might also like