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

C++ unit 2

This document provides a comprehensive overview of functions in C++, including their syntax, types, and usage. It covers key concepts such as function declaration, calling, definitions, passing arguments by value and reference, inline functions, function overloading, and the structure of classes and objects. Additionally, it explains access specifiers and member functions, illustrating these concepts with example code snippets.

Uploaded by

kittylite25kk
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)
11 views

C++ unit 2

This document provides a comprehensive overview of functions in C++, including their syntax, types, and usage. It covers key concepts such as function declaration, calling, definitions, passing arguments by value and reference, inline functions, function overloading, and the structure of classes and objects. Additionally, it explains access specifiers and member functions, illustrating these concepts with example code snippets.

Uploaded by

kittylite25kk
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/ 22

UNIT - II

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.

main() Function in C++


• 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()
Example

#include<stdio.h>
void main()
{
cout<<"This is main function";
}
Output

This is main function


C++ Function Prototype
A function prototype is a declaration of the function that tells the program about
the type of the value returned by the function and the number and type of arguments.
function prototype has the following parts :
• return type
• name of the function
• argument list
Eg: int sum(int n1, int n2); Here,
• return type - int
• name of the function - sum
• argument list - (int n1, int n2)
A function prototype can either appear before the definition of calling the function
(such prototypes are known as a global prototypes) or within the definition of calling
function (such prototypes are known as local prototypes).
C++ Function Definition
The general form of a function definition is as given below:
return_type function_name(parameter list)
{
body of the function
}

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;

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

inline int cube(int s)


{
return s*s*s;
}
int main()
{
int a = 11;
cout << "The cube of 3 is: " << cube(3) << "n";
return 0;
}
Advantages:
• Inline function is an optimization technique used by the compilers especially to
reduce the execution time.
• In inline functions, the compiler replaces the function call statement with the
function code itself (process called expansion) and then compiles the entire
code. So, with inline functions, the compiler does not have to jump to another
location to execute the function, and then jump back as the code of the called
function is already available to the calling program.
• It speeds up your program by avoiding function calling overhead.
• It saves overhead of return call from a function.
The compiler may not perform inlining in the following circumstances:
• If a function contains a loop. (for, while, do-while)
• If a function is recursive.
• If a function contains a switch command or goto statement.
FUNCTION OVERLOADING IN C++
Types of overloading in C++ are:
o Function overloading
o Operator overloading
C++ Function Overloading
• Function Overloading is defined as the process of having two or more function
with the same name, but different in parameters is known as function
overloading in C++.
• In function overloading, the function is redefined by using either different types
of arguments or a different number of arguments. It is only through these
differences compiler can differentiate between the functions.

Key principles of function overloading:


• Same Function Name:
All overloaded functions must have the same name.
• Different Parameter Lists:
The key factor for distinguishing overloaded functions is their parameter list, which can
differ in terms of the number of parameters, their data types, or the order in which they
are listed.
• Return Type is Ignored:
The return type of the overloaded functions does not affect whether they are considered
overloaded; you can have different return types for overloaded functions.
• Scope Matters:
Function overloading is only applicable within the same scope, meaning functions
defined in different namespaces or classes cannot be overloaded with each other.
Important points to consider:
• Ambiguity:
If the compiler cannot definitively determine which overloaded function to call based
on the arguments provided, it will result in a compilation error due to ambiguity.
• Default Arguments:
When using default arguments in overloaded functions, be cautious as they can
sometimes lead to ambiguity issues.

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

Syntax for class definition:


class class_name
{
private:
member variable declaration;
member function declaration;
private:
member variable declaration;
member function declaration;
};

Defining Class and Declaring Objects


• A class is defined in C++ using keyword class followed by the name of class. The
body of class is defined inside the curly brackets and terminated by a semicolon
at the end.

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;

2. Accessing data members and member functions:


Member function declaration:
type method_name (parameter-list)
{
method-body;
}

Method declaration have four parts:


• Name of the method (Method Name)
• The type of the value the method returns (Type)
• A List of Parameters ( Parameter-List)
• The body of the method

The data members and member functions of class can be accessed using the dot(‘.’)
operator with the object.

Member Function Definition:

There are 2 ways to define a member function:


1. Inside class definition
2. Outside class definition

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

3. Private Member Function


• A function declared inside the class's private section is known as "private
member function". A private member function is accessible through the only
public member function.

#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

4. Access Specifiers in C++


• Access Modifiers or Access Specifiers in a class are used to set the accessibility of
the class members. That is, it sets some restrictions on the class members not to
get directly accessed by the outside functions.

There are 3 types of access modifiers available in C++:


1. Public
2. Private
3. Protected

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;

cout << "Radius is: " << obj.radius << "\n";


cout << "Area is: " << obj.compute_area();
return 0;
}
Output:
Radius is: 5.5
Area is: 94.985
Private: The class members declared as private can be accessed only by the functions
inside the class. They are not allowed to be accessed directly by any object or function
outside the class.
Only the member functions or the friend functions are allowed to access the private
data members of a class.

Example:

#include<iostream>
class Circle
{
// private data member
private:
double radius;

public:
double compute_area()
{
return 3.14*radius*radius;
}

};
int main()
{
Circle obj;

// trying to access private data member


// directly outside the class
obj.radius = 1.5;
cout << "Area is:" << obj.compute_area();
return 0;
}
The output of above program will be a compile time error because we are not allowed
to access the private data members of a class directly outside the class.
Output:
In function 'int main()':
11:16: error: 'double Circle::radius' is private
double radius;

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.

CHARACTERISTICS OF MEMBER FUNCTIONS IN C++

➢ A member function in C++ is a function that is part of a class. It is used to


manipulate the data members of the class. Member functions are also known as
methods.
➢ Member functions are declared inside the class definition and can be defined
either inside or outside the class definition. A function declared as a member of
the class is called a member function.
➢ Generally, member functions are declared as public because they have to be
called outside of the class.
➢ Member functions, whether static or nonstatic, can be defined either in or
outside the class declaration.
➢ If a member function is defined inside a class declaration, it is treated as an inline
function, and there is no need to qualify the function name with its class name.
Although functions defined inside class declarations are already treated as inline
functions, you can use the inline keyword to document code.

How to define Member Functions in C++?


There are mainly two ways to define Member Function in C++.
1. Definition within the Class
2. Definition outside the Class
Outside the Class:
➢ Defining a member function outside a class requires the function declaration
(function prototype) to be provided inside the class definition. The member
function is declared inside the class like a normal function.
➢ This declaration informs the compiler that the function is a member of the class
and that it has been defined outside the class. After a member function is
declared inside the class, it must be defined (outside the class) in the program.
➢ The definition of member function outside the class differs from normal function
definition, as the function name in the function header is preceded by the class
name and the scope resolution operator (: :).
➢ The scope resolution operator informs the compiler what class the member
belongs to.
➢ The syntax for defining a member function outside the class is
Return_type class_name :: function_name (parameter_list) {
// body of the member function
}

Example : Definition of member function outside the class


class book {
// body of the class
};
void book :: getdata(char a[],float b) {
// defining member function outside the class
strcpy(title,a):
price = b:
}
void book :: putdata () {
cout<<"\nTitle of Book: "<<title;
cout<<"\nPrice of Book: "<<price;
}

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.

Example : Definition of a member function inside a class


class book {
char title[30];
float price;
public:
void getdata(char [],float); II declaration
void putdata()//definition inside the class {
cout<<"\nTitle of Book: "<<title;
cout<<"\nPrice of Book: "<<price;
};

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

➢ Data hiding is a fundamental concept of object-oriented programming. It


restricts the access of private members from outside of the class.
➢ However, there is a feature in C++ called friend functions that break this rule
and allow us to access member functions from outside the class.
➢ C++ provides a facility for accessing private and protected data by means of a
special feature called “friend” function

Definition: A friend function in C++ is a function that is preceded by the keyword


“friend”. When the function is declared as a friend, then it can access the private and
protected data members of the class.

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.

How constructors are different from a normal member function?


➢ Constructor has same name as the class itself .
➢ Constructors don’t have return type and it is always public.
➢ A constructor is automatically called when an object is created.

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]

A Parameterized Constructor is a constructor that can accept one or more arguments.


This helps programmers assign varied initial values to an object at the creation time.
class Rectangle
{ int main() {
private: // Create an object of Rectangle class
int length; Rectangle rect1(20, 15);
int width; Rectangle rect2; // Uses default
values 10 and 5
public:
// Constructor to initialize data cout << "Area of rect1: " <<
members with constants rect1.area() << endl;
Rectangle(int l = 10, int w = 5) cout << "Area of rect2: " <<
{ rect2.area() << endl;
length = l;
width = w; return 0;
} }
// Function to calculate area
int area() Output:
{
return length * width; Area of rect1: 300
}
}; Area of rect2: 50

You might also like