0% found this document useful (0 votes)
12 views23 pages

C++ 2

This document provides an overview of functions in C++, including their definition, advantages, and various types such as library and user-defined functions. It explains key concepts like function prototyping, calling methods (call by value, call by reference, and call by address), inline functions, default arguments, and passing arrays and structures to functions. Additionally, it includes examples to illustrate these concepts and their syntax.

Uploaded by

kowsalyaproj
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views23 pages

C++ 2

This document provides an overview of functions in C++, including their definition, advantages, and various types such as library and user-defined functions. It explains key concepts like function prototyping, calling methods (call by value, call by reference, and call by address), inline functions, default arguments, and passing arrays and structures to functions. Additionally, it includes examples to illustrate these concepts and their syntax.

Uploaded by

kowsalyaproj
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 23

UNIT – II: FUNCTIONS

Functions – Function Prototyping – Call by Value – Call by Reference – Inline Functions –


Default Arguments – Passing Arrays to Functions – Passing Structures to Functions – Recursion
– Pointers – Function Overloading – Friend Functions.

2.1 Functions

In C++, a function is a group of statements that is given a name, and which can be
called from some point of the program.

The most common syntax to define a function is:


return_type function_name ( parameter1, parameter2, ...)
{
statements
}
Where:
- return_type is the type of the value returned by the function.
- function_name is the identifier by which the function can be called.
- parameters (as many as needed): Each parameter consists of a type followed by an
identifier, with each parameter being separated from the next by a comma
- statements is the function's body. It is a block of statements surrounded by braces { } that
specify what the function actually does.

Advantages:
• Reusability:
A function once written can be invoked again and again, thus helping us to
reuse the code and removing data redundancy.
• Modularity:
Functions can help us in breaking a large, hard to manage problem into
smaller manageable sub-problems.
• Reduced Program Size:
Functions can reduce the size of the program by removing data
redundancy.
• Easy Debugging:
Using functions, debugging of a program becomes very easy, as it is
easier to locate and rectify the bug in the program if functions are used.
• Easy Updating:
If we need to update some code in the program, then it is much more easier in case we
have used functions, as the changes need to be made in one place only (in function).

A.PRAKASH (GL),PG & RESEARCH DEPARTMENT OF COMPUTER SCIENCE , ARIGNAR ANNA GOVERNMENT ARTS
COLLEGE , CHEYYAR-604 407 Page 1
C++ functions are classified in two categories. They are

• Library functions and


• User-defined functions.

The library functions can be used in any program by including respective header files.
The header files must be included using #include pre-processor directive. For example, a
mathematical function uses math.h header file. The programmer can also define and use his/her
own functions for performing some specific tasks. Such functions are called user-defined
functions.

Parts of A Function: Parts of a function are as follows.


1. Function prototype declaration
2. Function call
3. Definition of a function
4. Actual and formal arguments
5. Return statement

1. Function prototype Declaration:


A function prototype declaration consists of function’s return type, name, and
arguments list. The statements given below are the examples of function prototypes.

A.PRAKASH (GL),PG & RESEARCH DEPARTMENT OF COMPUTER SCIENCE , ARIGNAR ANNA GOVERNMENT ARTS
COLLEGE , CHEYYAR-604 407 Page 2
void show (void);
float sum (float, int);
float sum (float x, int y);

2. Function Call:
A function must be called by its name followed by argument, or without argument,
list enclosed in parenthesis and terminated by semicolon.
Syntax of function call is as follows:
function-name(with/without argument list);
In the above statement, function-name is the name of the function, arguments are
within the bracket and arguments are separated by comma. If arguments are absent one
can write void within the bracket.
3. Function Definition:
The first line is called function definition and function body follows it. The function
definition and function prototype should match with each other. The function body is
enclosed within curly braces. The function can be defined anywhere. If the function is
defined before its caller, then its prototype declaration is optional.
Syntax of function call is as follows:
return_data_type function-name(argument/parameter list);
{
variable declarations
function statements
}
4. Actual and Formal Argument:
The arguments declared in caller function and given in the function call are called
actual arguments.The arguments declared in the function definition are known as formal
arguments.
5. The return Statement:
The return statement is used to return value to the caller function. The return statement
returns only one value at a time. When a return statement is encountered , complier
transfers the control of the program to caller function.
The syntax of return statement is as follows:
return (variable name); or
return variable name;

2.3 Passing Arguments:


The main objective of passing argument to function is message passing. The message
passingis also known as communication between two functions, that is between caller and
called functions.

A.PRAKASH (GL),PG & RESEARCH DEPARTMENT OF COMPUTER SCIENCE , ARIGNAR ANNA GOVERNMENT ARTS
COLLEGE , CHEYYAR-604 407 Page 3
There are three methods:

1. Call by value (pass by value)


2. Call by address (pass by address)
3. Call by reference (pass by reference)

2.3 Call by Value:

In this type, values of actual arguments are passed to the formal arguments and
operation is done on the formal arguments. Any change in the formal arguments does not effect
to the actual arguments because formal arguments are photocopy of actual arguments. Changes
made in the formal arguments are local to the block of called function. Once control returns back
to the calling function, the changes made will vanish.

The following example illustrates the use of call by value.


#include<iostream>
using namespace std;
void swap (int, int);

int main()
{
int x,y;
cout<<“\n Enter Values of X & Y:”;
cin>>x>>y;
cout<<“\n\n In function main() before swap()”;
cout<<“\n Values X=”<<x <<“ and Y= ”<<y;
swap(x,y);
cout<<“\n\n In function main() after swap() ”;
cout<<“\n Values X=”<<x <<“ and Y= ”<<y;
return 0;
}
void swap(int a, int b)
{
int k;
k=a;
a=b;
b=k;
cout<<“\n In function swap() ”;
cout<<“\n Values X=”<<a <<“ and Y= ”<<b;
}

A.PRAKASH (GL),PG & RESEARCH DEPARTMENT OF COMPUTER SCIENCE , ARIGNAR ANNA GOVERNMENT ARTS
COLLEGE , CHEYYAR-604 407 Page 4
Output:
Enter Values of X & Y :5 4
In function main() before swap() Values X=5 and Y= 4
In function swap() Values X=4 and Y= 5
In function main() after swap() Values X=5 and Y= 4

Call by Address:
In this type, instead of passing values, addresses of actual parameters are
passed to the function by using pointers. Function operates on addresses rather than values. Here
the formal arguments are pointers to the actual arguments. Because of this, when the values of
formal arguments are changed, the values of actual parameters also change. Hence changes made
in the argument are permanent. The following example illustrates passing the arguments to the
function using call by address method.

#include<iostream>
using namespace std;
void swap (int *, int *);
int main()
{
int x,y;
cout<<“\n Enter Values of X & Y:”;
cin>>x>>y;
swap(&x,&y);
cout<<“\n In main() Values X=”<<x <<“ and Y=”<<y;
return 0;
}
void swap(int *a, int *b)
{
int *k;
*k=*a;
*a=*b;
*b=*k;
cout<<“\n In swap() Values X=”<<*a <<“ and Y=”<<*b;
}

OUTPUT
Enter Values of X & Y :5 4

A.PRAKASH (GL),PG & RESEARCH DEPARTMENT OF COMPUTER SCIENCE , ARIGNAR ANNA GOVERNMENT ARTS
COLLEGE , CHEYYAR-604 407 Page 5
In swap()Values X=4 and Y=5
In main()Values X=4 and Y=5

2.4 Call by Reference:


C passes arguments by value and address. In C++ it is possible to pass arguments by
reference. C++ reference types, declared with ‘&’ operator, they declare aliases for objects
variables and allow the programmer to pass arguments by reference to functions. The reference
decelerator (&) can be used to declare references outside functions.

For Ex.
int k = 0;
int &kk = k; // kk is an alias for k
kk = 2; // same effect as k = 2

Example:

#include<iostream>
using namespace std;
void swap (int &, int &);
cout<<“\n Enter Values of X & Y:”;
cin>>x>>y;
swap(x,y);
cout<<“\n In main()Values X=”<<x <<“ and Y=”<<y;
return 0;
}
void swap(int &a, int &b)
{
int k;
k=a;
a=b;
b=k;
cout<<“\n In swap()Values X=”<<a <<“ and Y=”<<b;
}

Output:

Enter Values of X & Y :5 4


In swap()Values X=4 and Y=5
In main()Values X=4 and Y=5

A.PRAKASH (GL),PG & RESEARCH DEPARTMENT OF COMPUTER SCIENCE , ARIGNAR ANNA GOVERNMENT ARTS
COLLEGE , CHEYYAR-604 407 Page 6
2.5 Inline Functions:
When a function is declared as inline, the compiler copies the code of the
function in the calling function. i.e., function body is inserted in place of function call during
compilation.

Syntax:

inline function_name(with or without arguments)


{
statement 1;
statement 2;
}
Following are few situations where inline functions may not work:
1. The function should not be recursive.
2. Function should not contain static variables.
3. Function containing control structure statements such as switch, if, for loop, etc.
4. The function main() cannot be used as inline.

The inline functions are similar to macros of C. The main limitation of macros is that they
are not functions, and errors are not checked at the time of compilation. The function offers
better type testing and does not contain limitations as present in macros.

Consider the following example:

#include <iostream>
using namespace std;
inline int Max(int x, int y)
{
return (x > y)? x : y;
}
int main( )
{
cout << "Max (20,10): " << Max(20,10) << endl;
cout << "Max (0,200): " << Max(0,200) << endl;
cout << "Max (100,1010):"<<Max(100,1010)<<endl;

A.PRAKASH (GL),PG & RESEARCH DEPARTMENT OF COMPUTER SCIENCE , ARIGNAR ANNA GOVERNMENT ARTS
COLLEGE , CHEYYAR-604 407 Page 7
return 0;
}

Output:
Max (20,10): 20
Max (0,200): 200
Max (100,1010):1010

2.6 Default Arguments:


A default argument is a value provided in function declaration that is automatically
assigned by the compiler if the caller of the function does not provide value for the argument.

Ex:
#include <iostream>
using namespace std;
int sum(int a, int b=10, int c=20, int d=30)
{
return a+b+c+d;
}
int main() {
int a=2,b=3,c=4,d=5;
cout<<"Sum:"<<sum(a,b,c,d)<<endl;
cout<<"Sum:"<<sum(a,b,c)<<endl;
cout<<"Sum:"<<sum(a,b)<<endl;
cout<<"Sum:"<<sum(a)<<endl;
return 0;
}
Output:
Sum:14
Sum:39
Sum:55
Sum:62

Const Arguments:
The constant variable can be declared using const keyword. The const keyword makes
variable value stable.

A.PRAKASH (GL),PG & RESEARCH DEPARTMENT OF COMPUTER SCIENCE , ARIGNAR ANNA GOVERNMENT ARTS
COLLEGE , CHEYYAR-604 407 Page 8
Ex. The following program generates an error

#include <iostream>
using namespace std;
int increment(const int a);
int main() {
int a=2;
cout<<"Incremented val:"<<increment(a);
return 0;
}
int increment( const int a)
{
return ++a;
}

Output:
error: increment of read-only parameter 'a'

2.7 Passing Arrays to Functions:


we can pass array as an argument to a function just like you pass variables as
arguments. In order to pass array to the function you just need to mention the array name
during function call like this:

function_name(array_name);

Example: Passing arrays to a function

In this example, we are passing two arrays a & b to the function sum(). This function adds
the corresponding elements of both the arrays and display them.

#include <iostream>
using namespace std;
/* This function adds the corresponding
* elements of both the arrays and
* displays it.
*/
void sum(int arr1[], int arr2[]){
int temp[5];
for(int i=0; i<5; i++){
temp[i] = arr1[i]+arr2[i];
cout<<temp[i]<<endl;
}
}
int main(){
int a[5] = {10, 20, 30, 40 ,50};

A.PRAKASH (GL),PG & RESEARCH DEPARTMENT OF COMPUTER SCIENCE , ARIGNAR ANNA GOVERNMENT ARTS
COLLEGE , CHEYYAR-604 407 Page 9
int b[5] = {1, 2, 3, 4, 5};
//Passing arrays to function
sum(a, b);
return 0;
}

Output:

11
22
33
44
55

Example 2: Passing multidimensional array to function

In this example we are passing a multidimensional array to the function square which
displays the square of each element.
#include <iostream>
#include <cmath>
using namespace std;
/* This method prints the square of each
* of the elements of multidimensional array
*/
void square(int arr[2][3]){
int temp;
for(int i=0; i<2; i++){
for(int j=0; j<3; j++){
temp = arr[i][j];
cout<<pow(temp, 2)<<endl;
}
}
}
int main(){
int arr[2][3] = {
{1, 2, 3},
{4, 5, 6}
};
square(arr);
return 0;
}
Output:

1
4
9
16
25
36

2.8 Passing Structures to Functions:

A.PRAKASH (GL),PG & RESEARCH DEPARTMENT OF COMPUTER SCIENCE , ARIGNAR ANNA GOVERNMENT ARTS
COLLEGE , CHEYYAR-604 407 Page 10
A structure variable can be passed to a function in similar way as normal argument.
Consider this example:

#include <iostream>
using namespace std;

struct Person {
char name[50];
int age;
float salary;
};

void displayData(Person); // Function declaration

int main() {
Person p;

cout << "Enter Full name: ";


cin.get(p.name, 50);
cout << "Enter age: ";
cin >> p.age;
cout << "Enter salary: ";
cin >> p.salary;
// Function call with structure variable as an argument
displayData(p);

return 0;
}

void displayData(Person p) {
cout << "\nDisplaying Information." << endl;
cout << "Name: " << p.name << endl;
cout <<"Age: " << p.age << endl;
cout << "Salary: " << p.salary;
}

Output

Enter Full name: Bill Jobs


Enter age: 55
Enter salary: 34233.4

Displaying Information.
Name: Bill Jobs
Age: 55
Salary: 34233.4

In this program, user is asked to enter the name , age and salary of a Person inside main() function.
Then, the structure variable p is to passed to a function using.

displayData(p);

A.PRAKASH (GL),PG & RESEARCH DEPARTMENT OF COMPUTER SCIENCE , ARIGNAR ANNA GOVERNMENT ARTS
COLLEGE , CHEYYAR-604 407 Page 11
The return type of displayData() is void and a single argument of type structure Person is passed.
Then the members of structure p is displayed from this function.

2.9 Recursion:
In many programming languages including C++, it is possible to call a function
from a same function. This function is known as recursive function and this programming
technique is known as recursion.

In recursion a function calls itself and the control goes to the same function and it
executes repeatedly until some condition is satisfied. In this type of recursive calls a
function starts with a new value every time.

Rules for Recursive Function


1. In recursion, it is essential to call a function by itself; otherwise recursion would
not take place.
2. Only the user-defined function can be involved in the recursion. Library function
cannot involve in recursion because their source code cannot be viewed.
3. A recursive function can be invoked by itself or by other function. It saves return
address with the intention to return at proper location when return to a calling statement
is made. The last-in-first-out nature of recursion indicates that stack data structure can
be used to implement it.
4. To stop the recursive function, it is necessary to base the recursion on test
condition, and proper terminating statement such as exit() or return() must be written
using the if() statement.

Example:
#include<iostream>
using namespace std;

int main()
{
unsigned long int fact(int);
dint f,x; cout<<“\nEnter a Number:”;
cin>>x; f=fact(x);
cout<<“\nFactorial of ” <<x <<“ is ”<<f;
return 0;
}
unsigned long int fact(int a)
{
unsigned long factorial;
if(a==1)

A.PRAKASH (GL),PG & RESEARCH DEPARTMENT OF COMPUTER SCIENCE , ARIGNAR ANNA GOVERNMENT ARTS
COLLEGE , CHEYYAR-604 407 Page 12
return 1;
else
factorial=a*fact(a-1);
return factorial;
}

Output:
Enter a Number:6
Factorial of 6 is 720

2.10 Pointers:
Pointers are symbolic representation of addresses. They enable programs to
simulate call-by-reference as well as to create and manipulate dynamic data structures. It’s
general declaration in C/C++ has the format :
Syntax:

datatype *var_name;
int *ptr; //ptr can point to an address which holds int data

How to use a pointer?


➢ Define a pointer variable
➢ Assigning the address of a variable to a pointer using unary operator (&) which returns
the address of that variable.
➢ Accessing the value stored in the address using unary operator (*) which returns the value
of the variable located at the address specified by its operand.

A.PRAKASH (GL),PG & RESEARCH DEPARTMENT OF COMPUTER SCIENCE , ARIGNAR ANNA GOVERNMENT ARTS
COLLEGE , CHEYYAR-604 407 Page 13
The reason we associate data type to a pointer is that it knows how many bytes the
data is stored in. When we increment a pointer, we increase the pointer by the size of data
type to which it points.

// C++ program to illustrate Pointers in C++


#include <stdio.h>

void geeks()
{
int var = 20;

// declare pointer variable


int *ptr;

// note that data type of ptr and var must be same


ptr = &var;

// assign the address of a variable to a pointer


printf("Value at ptr = %p \n",ptr);
printf("Value at var = %d \n",var);
printf("Value at *ptr = %d \n", *ptr);
}

// Driver program
int main()
{
geeks();
}

Output:
Value at ptr = 0x7ffcb9e9ea4c

A.PRAKASH (GL),PG & RESEARCH DEPARTMENT OF COMPUTER SCIENCE , ARIGNAR ANNA GOVERNMENT ARTS
COLLEGE , CHEYYAR-604 407 Page 14
Value at var = 20
Value at *ptr = 20

References and Pointers:

There are 3 ways to pass C++ arguments to a function:


• call-by-value
• call-by-reference with pointer argument
• call-by-reference with reference argument

// C++ program to illustrate call-by-methods in C++

#include <bits/stdc++.h>
using namespace std;
//Pass-by-Value
int square1(int n)
{
//Address of n in square1() is not the same as n1 in main()
cout << "address of n1 in square1(): " << &n << "\n";

// clone modified inside the function


n *= n;
return n;
}
//Pass-by-Reference with Pointer Arguments
void square2(int *n)
{
//Address of n in square2() is the same as n2 in main()
cout << "address of n2 in square2(): " << n << "\n";

// Explicit de-referencing to get the value pointed-to


*n *= *n;
}
//Pass-by-Reference with Reference Arguments
void square3(int &n)
{
//Address of n in square3() is the same as n3 in main()
cout << "address of n3 in square3(): " << &n << "\n";

// Implicit de-referencing (without '*')


n *= n;
}
void geeks()
{
//Call-by-Value
int n1=8;
cout << "address of n1 in main(): " << &n1 << "\n";
cout << "Square of n1: " << square1(n1) << "\n";
cout << "No change in n1: " << n1 << "\n";

A.PRAKASH (GL),PG & RESEARCH DEPARTMENT OF COMPUTER SCIENCE , ARIGNAR ANNA GOVERNMENT ARTS
COLLEGE , CHEYYAR-604 407 Page 15
//Call-by-Reference with Pointer Arguments
int n2=8;
cout << "address of n2 in main(): " << &n2 << "\n";
square2(&n2);
cout << "Square of n2: " << n2 << "\n";
cout << "Change reflected in n2: " << n2 << "\n";

//Call-by-Reference with Reference Arguments


int n3=8;
cout << "address of n3 in main(): " << &n3 << "\n";
square3(n3);
cout << "Square of n3: " << n3 << "\n";
cout << "Change reflected in n3: " << n3 << "\n";

}
//Driver program
int main()
{
geeks();
}

Output:

address of n1 in main(): 0x7ffcdb2b4a44


address of n1 in square1(): 0x7ffcdb2b4a2c
Square of n1: 64
No change in n1: 8
address of n2 in main(): 0x7ffcdb2b4a48
address of n2 in square2(): 0x7ffcdb2b4a48
Square of n2: 64
Change reflected in n2: 64
address of n3 in main(): 0x7ffcdb2b4a4c
address of n3 in square3(): 0x7ffcdb2b4a4c
Square of n3: 64
Change reflected in n3: 64

2.13 Function Overloading:


Function overloading is a feature of object oriented programming where two or
more functions can have the same name but different parameters .
When a function name is overloaded with different jobs it is called Function
Overloading.

A.PRAKASH (GL),PG & RESEARCH DEPARTMENT OF COMPUTER SCIENCE , ARIGNAR ANNA GOVERNMENT ARTS
COLLEGE , CHEYYAR-604 407 Page 16
In Function Overloading “Function” name should be the same and the arguments
should be different.
Function overloading can be considered as an example of polymorphism feature in
C++.

Following is a simple C++ example to demonstrate function overloading:

#include <iostream>

using namespace std;

void print(int i) {
cout << " Here is int " << i << endl;
}
void print(double f) {
cout << " Here is float " << f << endl;
}
void print(char const *c) {
cout << " Here is char* " << c << endl;
}

int main() {
print(10);
print(10.10);
print("ten");
return 0;
}

Output:
Here is int 10
Here is float 10.1
Here is char* ten
How Function Overloading works?

• Exact match:- (Function name and Parameter)


• If a not exact match is found:–
->Char, Unsigned char, and short are promoted to an int.
->Float is promoted to double
• If no match found:
->C++ tries to find a match through the standard conversion.

• ELSE ERROR

A.PRAKASH (GL),PG & RESEARCH DEPARTMENT OF COMPUTER SCIENCE , ARIGNAR ANNA GOVERNMENT ARTS
COLLEGE , CHEYYAR-604 407 Page 17
2.12 FRIEND FUNCTIONS:
The private members cannot be accessed from outside the class. i.e.… a non member
function cannot have an access to the private data of a class. In C++ a non member
function can access private by making the function friendly to a class.

Definition:

A friend function is a function which is declared within a class and is defined


outside the class. It does not require any scope resolution operator for defining . It can
access private members of a class. It is declared by using keyword “friend”

Ex:

class sample
{
int x,y;
public:
sample(int a,int b);
friend int sum(sample s);
};
sample::sample(int a,int b)
{
x=a;y=b;
}
int sum(samples s)
{
int sum;
sum=s.x+s.y;
return 0;
}
void main()
{
Sample obj(2,3);
int res=sum(obj);
cout<< “sum=”<<res<<endl;
}

A friend function possesses certain special characteristics:


➢ It is not in the scope of the class to which it has been declared as friend.

A.PRAKASH (GL),PG & RESEARCH DEPARTMENT OF COMPUTER SCIENCE , ARIGNAR ANNA GOVERNMENT ARTS
COLLEGE , CHEYYAR-604 407 Page 18
➢ Since it is not in the scope of the class, it cannot be called using the object of
that class. It can be invoked like a normal function without the help of any
object.
➢ Unlike member functions, it cannot access the member names directly and has to
use an object name and dot membership operator with each member name.
➢ It can be declared either in the public or private part of a class without affecting
its meaning.
➢ Usually, it has the objects as arguments.
#include<iostream.h>
class sample
{
Int a;
int b;
public:
void setvalue()
{
a=25;
b=40;
}
friend float mean(sample s);
};
float mean(sample s)
{
return float(s.a+s.b)/2.0;
}
int main()
{
sample X;
X.setvalue();
cout<<”Mean value=”<<mean(X);
return 0;
}
write a program to find max of two numbers using friend function for two different classes:
#include<iostream>
using namespace std;
class sample2;
class sample1
{
int x;
public:

A.PRAKASH (GL),PG & RESEARCH DEPARTMENT OF COMPUTER SCIENCE , ARIGNAR ANNA GOVERNMENT ARTS
COLLEGE , CHEYYAR-604 407 Page 19
sample1(int a);
friend void max(sample1 s1,sample2 s2)
};
sample1::sample1(int a)
{
x=a;
}
class sample2
{
int y;
public:
};
sample2(int b);
friend void max(sample1 s1,sample2 s2)
Sample2::sample2(int b)
{
y=b;
}
void max(sample1 s1,sample2 s2)
{
If(s1.x>s2.y)
cout<<”Data member in Object of class sample1 is larger ”<<endl;
else
}
cout<<”Data member in Object of class sample2 is larger ”<<endl;
void main()
{
sample1 obj1(3);
sample2 obj2(5);
max(obj1,obj2);
}

Write a program to add complex numbers using friend function:


#include<iostream>
using namespace std;
class complex
{
float real,img;
public:
complex();
complex(float x,float y)

A.PRAKASH (GL),PG & RESEARCH DEPARTMENT OF COMPUTER SCIENCE , ARIGNAR ANNA GOVERNMENT ARTS
COLLEGE , CHEYYAR-604 407 Page 20
friend complex add_complex(complex c1,complex c2);
};
complex::complex()
{
real=img=0;
}
complex::complex(float x,float y)
{
real=x;img=y;
}
complex add_complex(complex c1,complex c2)
{
complex t;
t.real=c1.real+c2.real;
t.img=c1.img+c2.img;
return t;
}
void complex::display ()
{
if(img<0)
{
img=-img; cout<<real<<"-i"<<img<<endl
}
else
{
}
}
int main()
{
cout<<real<<"+i"<<img<<endl complex obj1(2,3);
complex obj2(-4,-6);
complex obj3=add_compex(obj1,obj2);
obj3.display();
return 0;
}
Friend Class:
A class can also be declared to be the friend of some other class. When we
create a friend class then all the member functions of the friend class also become the
friend of the other class.
This requires the condition that the friend becoming class must be first declared or
defined (forward declaration).
A.PRAKASH (GL),PG & RESEARCH DEPARTMENT OF COMPUTER SCIENCE , ARIGNAR ANNA GOVERNMENT ARTS
COLLEGE , CHEYYAR-604 407 Page 21
#include <iostream.h>
class sample_1
{
friend class sample_2;//declaring friend class
int a,b;
public: void getdata_1()
{
cout<<"Enter A & B values in class sample_1";
cin>>a>>b;
}
void display_1()
{
cout<<"A="<<a<<endl; cout<<"B="<<b<<endl;
}
};
class sample_2
{
int c,d,sum;
sample_1 obj1;
public: void getdata_2()
{
}
obj1.getdata_1();
cout<<"Enter C & D values in class sample_2";
cin>>c>>d;
void sum_2()
{
sum=obj1.a+obj1.b+c+d;
}
void display_2()
{
cout<<"A="<<obj1.a<<endl;
cout<<"B="<<obj1.b<<endl;
cout<<"C="<<c<<endl;
cout<<"D="<<d<<endl;
cout<<"SUM="<<sum<<endl;
}
};
int main()
{
sample_1 s1;

A.PRAKASH (GL),PG & RESEARCH DEPARTMENT OF COMPUTER SCIENCE , ARIGNAR ANNA GOVERNMENT ARTS
COLLEGE , CHEYYAR-604 407 Page 22
s1.getdata_1();
s1.display_1();
sample_2 s2;
s2.getdata_2();
s2.sum_2();
s2.display_2();
}
Enter A & B values in class sample_1:1 2 A=1 B=2
Enter A & B values in class sample_1:1 2 3 4
Enter C & D values in class sample_2:A=1 B=2 C=3 D=4 SUM=10

A.PRAKASH (GL),PG & RESEARCH DEPARTMENT OF COMPUTER SCIENCE , ARIGNAR ANNA GOVERNMENT ARTS
COLLEGE , CHEYYAR-604 407 Page 23

You might also like