C++ unit 2
C++ unit 2
Functions in C++
Functions are used to provide modularity to a program. Creating an application
using function makes it easier to understand, edit, check errors etc.
Elements of user-function functions: We need to establish 3 elements that are
related to functions.
• Function declaration / Function Prototyping
• Function call
• Function definition
Basic Syntax for using Functions in C++
return-type function-name(parameter1, parameter2, ...)
{
// function-body
}
• return-type: suggests what the function will return. It can be int, char, some
pointer or even a class object. There can be functions which does not return
anything, they are mentioned with void.
• Function Name: is the name of the function, using the function name it is
called.
• Parameters: are variables to hold values of arguments passed while function is
called. A function may or may not contain parameter list.
Example Program
// function for adding two values
void sum(int x, int y)
{
int z;
z = x + y;
cout << z;
}
int main()
{
int a = 10;
int b = 20;
// calling the function with name 'sum'
sum (a, b);
}
Here, a and b are two variables which are sent as arguments to the
function sum, and x and y are parameters which will hold values of a and b to
perform the required operation inside the function.
• Function body: is the part where the code statements are written.
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()
Example
#include<stdio.h>
void main()
{
cout<<"This is main function";
}
Output
PASSING ARGUMENTS
Call by Value
In call by value, the actual value that is passed as argument is not changed
after performing some operation on it. When call by value is used, it creates a copy of
that variable into the stack section in memory. When the value is changed, it changes
the value of that copy, the actual value remains the same.
Example Code
#include<iostream>
using namespace std;
void my_function(int x) {
x = 50;
cout << "Value of x from my_function: " << x << endl;
}
main() {
int x = 10;
my_function(x);
cout << "Value of x from main function: " << x;
}
Output
Value of x from my_function: 50
Value of x from main function: 10
Call by Reference
In call by reference the actual value that is passed as argument is changed after
performing some operation on it. When call by reference is used, it creates a copy of
the reference of that variable into the stack section in memory. Is uses a reference to
get the value. So when the value is changed using the reference it changes the value of
the actual variable.
Example Code
#include<iostream>
using namespace std;
main() {
int x = 10;
my_function(x);
cout << "Value of x from main function: " << x;
}
Output
Value of x from my_function: 50
Value of x from main function: 50
Where to use Call by reference?
• The call by reference is mainly used when we want to change the value of the
passed argument into the invoker function.
• One function can return only one value. When we need more than one value
from a function, we can pass them as an output argument in this manner.
INLINE FUNCTIONS
• An inline function is a function that is expanded in line when it is invoked.
• Functions can be instructed to compiler to make them inline, so that compiler can
replace those function definitions wherever those are being called.
• Compiler replaces the definition of inline functions at compile time instead of
referring function definition at run time.
• It is only a request to a compiler, not a command. If function is big (in term of
executable instruction etc) then, compiler can ignore the “inline” request and treat
the function as normal function.
Syntax:
inline function-header
{
function-body
}
Example
#include <iostream.h>
Example Program
FUNCTION OVERLOADING WITH FUNCTION OVERLOADING WITH
DIFFERENT NUMBER OF DIFFERENT TYPES OF ARGUMENTS:
ARGUMENTS:
#include<iostream.h> #include <iostream.h>
#include<conio.h> #include<conio.h>
int add(int,int);
int add(int,int,int); int sum (int a, int b)
int main() {
{ return a+b;
int a,b,c,twoarg,threearg; }
clrscr();
cout<<"\n Enter First Number:"; double sum (double a, double b)
cin>>a; {
cout<<"Enter Second Number:"; return a+b;
cin>>b; }
cout<<"\n Enter third Number:";
cin>>c; int main ()
cout<<"\n With two arguments"; {
twoarg=add(a,b); cout << sum (10,20) << '\n';
cout<<"Sum="<<twoarg; cout << sum (1.0,1.5) << '\n';
cout<<"\n With three Arguments"; return 0;
threearg=add(a,b,c); }
cout<<"Sum="<<threearg;
getch();
return 0;
}
add(int x, int y)
{
int result;
result = x+y;
return result;
}
add(int x, int y, int z)
{
int result;
result = x+y+z;
return result;
}
CLASSES AND OBJECTS IN C++
• A class is a user-defined data type. Once the class type has been defined, we can
create variables and functions of that class.
• Variables are called as Member variables and Functions are called as Member
functions.
1. Specifing a Class
A Class specification has 2 parts:
1. Class declaration
2. Class – Member function definition
Declaring Objects:
• Object is a runtime entity, it is created at runtime.
• Object is an instance of a class. All the members of the class can be accessed
through object.
Syntax to Define Object in C++
className objectVariableName;
The data members and member functions of class can be accessed using the dot(‘.’)
operator with the object.
To define a member function outside the class definition we have to use the scope
resolution :: operator along with class name and function name.
#include <iostream.h>
using namespace std;
class Game
{
public:
void play(); // Function declaration
};
// function definition outside the class
void Game::play()
{
cout << "Function defined outside the class.\n";
}
int main()
{
Game g;
g.play();
return 0;
}
Output:
1. Example program for class – Defining member function inside the class
#include<iostream.h>
#include<conio.h>
class circle
{
private:
float radius,area;
public:
void getdata()
{
cout<<"\n Enter the radius of a circle:";
cin>>radius;
}
void calculate()
{
area = 3.14*radius*radius;
cout<<"\n Area:"<<area;
}
};
int main()
{
clrscr();
circle c;
c.getdata();
c.calculate();
getch();
return 0;
}
#include<iostream.h>
#include<conio.h>
class student
{
private:
int rollno;
void read()
{
rollno=12;
}
public:
void show()
{
read();
cout<<”\n Rollno:”<<rollno;
}
};
void main()
{
student s;
s.show;
return0;
}
Output:
Roll no = 12
Public: All the class members declared under public will be available to everyone. The
data members and member functions declared public can be accessed by other classes
too. The public members of a class can be accessed from anywhere in the program using
the direct member access operator (.) with the object of that class.
Example Program:
#include<iostream>
using namespace std;
class Circle
{
public:
double radius;
double compute_area()
{
return 3.14*radius*radius;
}
};
int main()
{
Circle obj;
obj.radius = 5.5;
Example:
#include<iostream>
class Circle
{
// private data member
private:
double radius;
public:
double compute_area()
{
return 3.14*radius*radius;
}
};
int main()
{
Circle obj;
Protected: Protected access modifier is similar to that of private access modifiers, the
difference is that the class member declared as Protected are inaccessible outside the
class but they can be accessed by any subclass(derived class) of that class.
Note that the member functions of the class can access all the data members and
other member functions of the same class (private, public or protected) directly by using
their names. In addition, different classes can use the same function name.
Inside the Class:
➢ A member function of a class can also be defined inside the class. However, when
a member function is defined inside the class, the class name and the scope
resolution operator are not specified in the function header.
➢ Moreover, the member functions defined inside a class definition are by default
inline functions.
In this example, the member function putdata() is defined inside the class book. Hence,
putdata() is by default an inline function.
UNIT – II – PART II
FRIEND FUNCTION
Syntax:
class className
{
……
friend returnType functionName(arg list);
};
The function can be defined anywhere in the code file and we need not use the keyword
friend or the scope resolution, operator.
Example Program: void showbal(ac a)
#include<iostream.h> {
#include<conio.h> cout<<\n Balance is:<<a.bal;
class one }
{
private: int main()
char name[15]; {
int acno; ac k;
float bal; k.read;
public: showbal(k);
void read() return 0;
{ }
cout<<”\n Name:”;
cin>>name; Output:
cout<<”\n acno:”; Name: Krishna
cin>>acno; Ac.no: 1001
cout<<”\n bal:”; Balance: 40000
cin>>bal;
} Balance is: 40000 [ here friend
friend void showbal(ac); //friend function has accessed private
function declaration member outside of the class ]
};
Important Points about Friend Functions:
▪ A friend function can be declared in the private or public section of the class.
▪ It can be called like a normal function without using the object.
▪ A friend function is not in the scope of the class, of which it is a friend.
▪ A friend function is not invoked using the class object as it is not in the scope of
the class.
▪ A friend function cannot access the private and protected data members of the
class directly. It needs to make use of a class object and then access the
members using the dot operator.
C++ Constructors
• A constructor is a special member function of a class and shares the same
name as of class, which means the constructor and class have the same name.
• Constructor is called by the compiler whenever the object of the class is created,
it allocates the memory to the object and initializes class data members by
default values or values passed by the user while creating an object.
• Constructors don’t have any return type.
• Constructor functions are not inherited, and their addresses cannot be
referenced.
Syntax of Constructor
class class_name
{
public:
// declaring constructor
class_name({parameters})
{
// constructor body
}
};
In the above syntax, we can see the class has the name class_name and the constructor
have also the same name. A constructor can have any number of parameters as per
requirements. Also, there is no return type or return value of the constructor.
Example:
#include<iostream.h> Output:
#include<conio.h>
class MyClass Welcome
{
public:
MyClass()
{
cout<<"Welcome";
}
};
int main()
{
clrscr();
MyClass m;
getch();
return 0;
}
Types of Constructors:
1. Default Constructor:
A constructor which does not receive any parameters is called a Default
Constructor or a Zero Argument Constructor. Every class object is initialized with the
same set of values in the default constructor.
2. Parameterized Constructor: [Constructor with arguments]