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

Module 2

Functions in C++ allow programmers to organize code into reusable blocks. Functions take inputs, perform operations, and return outputs. They help reduce redundancy, make code more modular, and provide abstraction. Defining a function involves specifying its return type, name, parameters, and body. Functions are called by passing the required parameters and name. C++ also uses object-oriented programming concepts like classes, objects, encapsulation, inheritance, polymorphism, and abstraction.

Uploaded by

shahany habeeb
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
68 views

Module 2

Functions in C++ allow programmers to organize code into reusable blocks. Functions take inputs, perform operations, and return outputs. They help reduce redundancy, make code more modular, and provide abstraction. Defining a function involves specifying its return type, name, parameters, and body. Functions are called by passing the required parameters and name. C++ also uses object-oriented programming concepts like classes, objects, encapsulation, inheritance, polymorphism, and abstraction.

Uploaded by

shahany habeeb
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 27

1

FUNCTIONS IN C++

A function is a set of statements that take inputs, do some specific computation,  and
produce output. The idea is to put some commonly or repeatedly  done tasks together and
make a function so that instead of writing the same code again and again for different
inputs, we can call the function.

Why Do We Need Functions?


 Functions help us in reducing code redundancy. If functionality is performed at
multiple places in software, then rather than writing the same code, again and
again, we create a function and call it everywhere. This also helps in
maintenance as we have to change at one place if we make future changes to the
functionality.
 Functions make code modular. Consider a big file having many lines of code. It
becomes really simple to read and use the code if the code is divided into
functions.
 Functions provide abstraction. For example, we can use library functions
without worrying about their internal work.
Function Declaration

A function declaration tells the compiler about a function name and how to call the function.
The actual body of the function can be defined separately.

Defining a Function
2

 Return Type − A function may return a value. The return_type is the data


type of the value the function returns. Some functions perform the desired
operations without returning a value. In this case, the return_type is the
keyword void.
 Function Name − This is the actual name of the function. The function name
and the parameter list together constitute the function signature.
 Parameters − A parameter is like a placeholder. When a function is invoked,
you pass a value to the parameter. This value is referred to as actual parameter
or argument. The parameter list refers to the type, order, and number of the
parameters of a function. Parameters are optional; that is, a function may
contain no parameters.
 Function Body − The function body contains a collection of statements that
define what the function does.
Calling a Function
While creating a C++ function, you give a definition of what the function has to do. To use a
function, you will have to call or invoke that function.
When a program calls a function, program control is transferred to the called function. A
called function performs defined task and when it’s return statement is executed or when its
function-ending closing brace is reached, it returns program control back to the main
program.
To call a function, you simply need to pass the required parameters along with function
name, and if function returns a value, then you can store returned value

MAIN FUNCTION

A program shall contain a global function named main, which is the designated start of the
program in hosted environment.
Syntax of main() function:
A main() function declaration can be done in the following ways.

int main() {}
or
3

int main( int argc, char* argv[]) {}

Importance points of the main() function


1. An operating system always calls the main() function when a programmers or users execute
their programming code.
2. It is responsible for starting and ends of the program.
3. It is a universally accepted keyword in programming language and cannot change its meaning
and name.
4. A main() function is a user-defined function in C that means we can pass parameters to the
main() function according to the requirement of a program.
5. A main() function is used to invoke the programming code at the run time, not at the compile
time of a program.
6. A main() function is followed by opening and closing parenthesis brackets.

What is function prototyping?

A function prototype is basically a declaration of the function that tells the program about the type
of the value which is to be returned by the function. It also tells about the number and type of
arguments of the function
4

Call by Value and Call by Reference


Functions can be invoked in two ways: Call by Value or Call by Reference.
These two ways are generally differentiated by the type of values passed to them as
parameters. The parameters passed to function are called actual parameters whereas
the parameters received by function are called formal parameters.

Call By Value: In this parameter passing method, values of actual parameters are
copied to function’s formal parameters and the two types of parameters are stored in
different memory locations. So any changes made inside functions are not reflected
in actual parameters of the caller.
5

Call by Reference : Both the actual and formal parameters refer to the same locations,
so any changes made inside the function are actually reflected in actual parameters
of the caller.
6
7

Return by reference

int& fun(int &a){


cout << a << endl;
return a;
}
int main(){
int x = 10;
fun(x) = 25;
cout << x << endl;
}

Here, inside the main function, we have declared a variable x and initialized this variable
with a value of 10. Next, we are calling the function ‘fun’ by passing x. So, this function is
taking ‘a’ integer variable which is a reference to variable ‘x’. We know one thing when the
function returns something that returns value, we can take it in some variable i.e. ‘int y =
fun(x)’. Yes, return result we can take it in some variable, so function always comes on the
right side of the assignment. We don’t write them on the left-hand side.

Here ‘a’ is not a separate variable, it’s a reference to ‘x’. So, this is called by reference. ‘fun’
will display ‘a’, so it will display 10 then return ‘a’. So, the return type of function is ‘int &’.
It will not return the value of ‘’a, it will return the reference, reference of ‘x’ so when it
returns here this function ‘fun(x)’ becomes nothing but ‘x’.

So, this whole thing ‘fun(x)’ becomes X only. We can write here ‘fun(x) = 25’. So now you
can see an amazing thing here that our function is written on the left-hand side. And our
function is acting as a reference of this variable ‘x’.

Basic Concepts of Object Oriented Programming 


Object oriented programming is a type of programming which uses objects and classes its
functioning.
Some basic concepts of object oriented programming are −
 CLASS
8

 OBJECTS
 ENCAPSULATION
 POLYMORPHISM
 INHERITANCE
 ABSTRACTION
Class − A class is a data-type that has its own members i.e. data members and member
functions. It is the blueprint for an object in object oriented programming language. It is the
basic building block of object oriented programming in c++. The members of a class are
accessed in programming language by creating an instance of the class.
Some important properties of class are −
 Class is a user-defined data-type.
 A class contains members like data members and member functions.
 Data members are variables of the class.
 Member functions are the methods that are used to manipulate data members.
 Data members define the properties of the class whereas the member functions
define the behaviour of the class.

Object − An object is an instance of a class. It is an entity with characteristics and behaviour


that are used in the object oriented programming. An object is the entity that is created to
allocate memory. A class when defined does not have memory chunk itself which will be
allocated as soon as objects are created.

Encapsulation In object oriented programming, encapsulation is the concept of wrapping


together of data and information in a single unit. A formale defination of encapsulation would
be: encapsulation is binding togather the data and related function that can manipulate the
data.
9

Polymorphism The name defines polymorphism is multiple forms. which means


polymorphism is the ability of object oriented programming to do some work using multiple
forms. The behaviour of the method is dependent on the type or the situation in which the
method is called.

Inheritance it is the capability of a class to inherit or derive properties or characteristics


other class. it is very important and object oriented program as it allows reusability i.e. using
a method defined in another class by using inheritance. The class that derives properties from
other class is known as child class or subclass and the class from which the properties are
inherited is base class or parent class.
C ++ programming language supports the following types of inheritance
 single inheritance
 multiple inheritance
 multi level inheritance
 Hierarchical inheritance
 hybrid inheritance
Abstraction Data abstraction or Data Hiding is the concept of hiding data and showing only
relevant data to the final user. It is also an important part object oriented programing.
What is OOP?

OOP stands for Object-Oriented Programming . As you can guess from it’s name it breaks
the program on the basis of the objects in it. It mainly works on Class, Object,
Polymorphism, Abstraction, Encapsulation and Inheritance. Its aim is to bind together the
data and functions to operate on them.
Benefits of OOP
1. Re-usability
It means reusing some facilities rather than building them again and again. This is done with
the use of a class. We can use it ‘n’ number of times as per our need.
2. Data Redundancy
This is a condition created at the place of data storage (you can say Databases)where the
same piece of data is held in two separate places. So the data redundancy is one of the
greatest advantages of OOP. If a user wants a similar functionality in multiple classes, he/she
can go ahead by writing common class definitions for similar functionalities and inherit them.

3. Code Maintenance
10

This feature is more of a necessity for any programming languages; it helps users from doing
re-work in many ways. It is always easy and time-saving to maintain and modify the existing
codes by incorporating new changes into them.
4. Security
With the use of data hiding and abstraction mechanism, we are filtering out limited data to
exposure, which means we are maintaining security and providing necessary data to view.
5. Design Benefits
If you are practicing on OOPs, the design benefit a user will get is in terms of designing and
fixing things easily and eliminating the risks (if any). Here the Object-Oriented Programs
forces the designers to have a long and extensive design phase, which results in better designs
and fewer flaws. After a time when the program has reached some critical limits, it is easier
to program all the non-OOP’s one separately.
6. Better productivity
with the above-mentioned facts of using the application definitely enhances its users overall
productivity. This leads to more work done, finishing a better program, having more inbuilt
features, and easier reading, writing and maintaining. An OOP programmer cans stitch new
software objects to make completely new programs. A good number of libraries with useful
functions in abundance make it possible.
8. Polymorphism Flexibility
Let’s see a scenario to better explain this behavior.
You behave in a different way if the place or surrounding gets change. A person will behave
like a customer if he is in a market, the same person will behave like a student if he is in a
school and as a son/daughter if put in a house. Here we can see that the same person showing
different behavior every time the surroundings are changed. This means polymorphism is
flexible and helps developers in a number of ways.
9. Problems solving
Decomposing a complex problem into smaller chunks or discrete components is a good
practice. OOP is specialized in this behavior, as it breaks down your software code into bite-
sized – one object at a time. The broken components can be reused in solutions to different
other problems (both less and more complex), or either they can be replaced by the future
modules that relate to the same interface with implementations details
Application of OOPs
 Real-Time System design: Real-time system inherits complexities and makes it
difficult to build them. OOP techniques make it easier to handle those
complexities.
 Hypertext and Hypermedia: Hypertext is similar to regular text as it can be
stored, searched, and edited easily. Hypermedia on the other hand is a superset
11

of hypertext. OOP also helps in laying the framework for hypertext and
hypermedia.
 AI Expert System: These are computer application that is developed to solve
complex problems which are far beyond the human brain. OOP helps to develop
such an AI expert System
 Office automation System: These include formal as well as informal electronic
systems that primarily concerned with information sharing and communication
to and from people inside and outside the organization. OOP also help in making
office automation principle.
 Neural networking and parallel programming: It addresses the problem of
prediction and approximation of complex-time varying systems. OOP simplifies
the entire process by simplifying the approximation and prediction ability of the
network.
 Stimulation and modeling system: It is difficult to model complex systems due
to varying specifications of variables. Stimulating complex systems require
modeling and understanding interaction explicitly. OOP provides an appropriate
approach for simplifying these complex models.
 Object-oriented database: The databases try to maintain a direct
correspondence between the real world and database object in order to let the
object retain it identity and integrity.
 Client-server system: Object-oriented client-server system provides the IT
infrastructure creating object-oriented server internet(OCSI) applications.
12

Specifying a class

Need for Class:


Class is a way to bind the data and its associated functions together.
Classes are needed to represent real world entities that not only have data type
properties but also have associated operations. It is used to create user defined
data type

Declaration of a class

Class Access Specifiers


Data hiding is one of the important features of Object Oriented Programming
which allows preventing the functions of a program to access directly the
internal representation of a class type. The access restriction to the class
members is specified by public, private, and protected sections within the class
body. The keywords public, private, and protected are called access specifiers.
The default access specifier for members is private.
13

The Public Members:

A public member is accessible from anywhere outside the class but within a
program. You can set and get the value of public data members even without
using any member function.
The Private Members:
A private member cannot be accessed from outside the class. Only the class
member functions can access private members. By default all the members of a
class would be private.
The Protected Members:
members cannot be accessed from outside the class, however, they can be accessed in inherited
classes. 

Definition of class members


Data members are the data variables that represent the features or properties of a
class. Member functions are the functions that perform specific tasks in a class.
Member functions are called as methods, and data members are also called as
attributes.

Defining methods of a class


(1) Inside the class definition
14

(2) Outside the class definition

(1) Inside the class definition: When a member function is defined inside a
class, it behaves like inline functions. These are called Inline member functions.

(2) Outside the class definition: When Member function defined outside the
class just like normal function definition (Function definitions you are familiar
with ) then it is be called as outline member function or non-inline member
function. Scope resolution operator (::) is used for this purpose. The syntax
for defining the outline member function is

Referencing class members


The members of a class are referenced (accessed) by using the object of the
class followed by the dot (membership) operator and the name of the member.

The general syntax for calling the member function is:

Object_name . function_name(actual parameter);

For example consider the following illustration


15

Read and Print Student Information Class Example Program

// Header Files
#include <iostream>
#include<conio.h>

using namespace std;


16

// Student Class Declaration


class StudentClass {
private:
char name[20];
int regNo, sub1, sub2, sub3;
float total, avg;

public:
void read() {
cout << "Enter Name :";
cin >> name;

cout << "Enter Registration Number :";


cin >> regNo;

cout << "Enter Marks for Subject 1,2 and 3 :";


cin >> sub1 >> sub2>> sub3;
}

void sum() {
total = sub1 + sub2 + sub3;
avg = total / 3;
}

void print() {
cout << "Name :" << name << endl;
cout << "Registration Number :" << regNo << endl;
cout << "Marks :" << sub1 << " , " << sub2 << " , " << sub3 << endl;
cout << "Total :" << total << endl;
cout << "Average :" << avg << endl;
}
};

int main() {
// Object Creation For Class
17

StudentClass stu1, stu2;

cout << "Read and Print Student Information Class Example Program In C++\n";

cout << "\nStudentClass : Student 1" << endl;


stu1.read();
stu1.sum();
stu1.print();

cout << "\nStudentClass : Student 2" << endl;


stu2.read();
stu2.sum();
stu2.print();
getch();
return 0;
}

Sample Output

Read and Print Student Information Class Example Program In C++


StudentClass : Student 1
Enter Name :Mask
Enter Registration Number :10001
Enter Marks for Subject 1,2 and 3 :90
80
65
Name :Mask
Registration Number :10001
Marks :90 , 80 , 65
Total :235
Average :78.3333
StudentClass : Student 2
Enter Name :Operas
Enter Registration Number :10002
Enter Marks for Subject 1,2 and 3 :95
85
18

70
Name :Operas
Registration Number :10002
Marks :95 , 85 , 70
Total :250
Average :83.3333

Private member function


How to access the Private Member Function in C++? 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.

 Using public and private in C++ Class


// Program to illustrate the working of
// public and private in C++ Class

#include <iostream>
using namespace std;

class Room {

private:
double length;
double breadth;
double height;

public:

// function to initialize private variables


void initData(double len, double brth, double hgt) {
length = len;
breadth = brth;
height = hgt;
}

double calculateArea() {
return length * breadth;
}

double calculateVolume() {
19

return length * breadth * height;


}
};

int main() {

// create object of Room class


Room room1;

// pass the values of private variables as arguments


room1.initData(42.5, 30.8, 19.2);

cout << "Area of Room = " << room1.calculateArea() << endl;


cout << "Volume of Room = " << room1.calculateVolume() << endl;

return 0;
}

Memory Allocation for Objects

Before using a member of a class, it is necessary to allocate the required memory space to


that member. The way the memory space for data members and member functions is
allocated is different regardless of the fact that both data members and member functions
belong to the same class.
The memory space is allocated to the data members of a class only when an object of the
class is declared, and not when the data members are declared inside the class. Since a single
20

data member can have different values for different objects at the same time, every object
declared for the class has an individual copy of all the data members.
On the other hand, the memory space for the member functions is allocated only once when
the class is defined. In other words, there is only a single copy of each member function,
which is shared among all the objects. For instance, the three objects, namely, book1, book2
and book3 of the class book have individual copies of the data members title and price.
However, there is only one copy of the member functions getdata () and putdata () that is
shared by all the three objects
21

Arrays within a Class


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

Static Data Members in C++


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;

The above syntax specifies how the static data member is declared and defined. They are
initialized during their definition outside the class explicitly. But unlike normal variables
and data members, they are initialized to 0 by default. The static data members are declared
and defined separately because all the data members (static or non-static) must be declared
inside the class, as class serves as a blueprint for creating objects and doesn’t allocate any
memory. So unlike normal data members that get memory (defined) corresponding to their
objects, the static data members who are not associated with any object needs to be defined
explicitly outside the class. The static data members remain in memory even though no
object of a class is created.
23

Static Member Function in C++


In a class, in addition to static member variables, static member functions can also be
declared. Ordinary member functions can access all members (including member variables
and member functions), and static member functions can only access static members.

Array of Objects in c++


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
24

#include<iostream>
using namespace std;
 
class Employee
{
  int id;
  char name[30];
  public:
   
  void getdata();
  
  void putdata();
};
 
void Employee::getdata()
{
  cout << "Enter Id : ";
  cin >> id;
  cout << "Enter Name : ";
  cin >> name;
}
 
void Employee::putdata()
{
  cout << id << " ";
  cout << name << " ";
  cout << endl;
}

int main()
{
 
  Employee emp[30];
  int n, i;
  cout << "Enter Number of Employees - ";
  cin >> n;
  
  for(i = 0; i < n; i++)
    emp[i].getdata();
   
  cout << "Employee Data - " << endl;
25

   
  for(i = 0; i < n; i++)
    emp[i].putdata();
}

Friend function in c++


A friend function of a class is defined outside that class' scope but it has the right to access all
private and protected members of the class. Even though the prototypes for friend functions
appear in the class definition, friends are not member functions.

 The friend function is outside the scope of the class to which it has been declared a
friend
 A friend function can either be a member of a class or a function declared outside the
scope of the class
 The friend functionality is not limited to a single class.
 Invoking a friend function is like invoking any normal function of the class without
using the object
 We cannot invoke the friend function using the object since it is not in the scope of
the class
 Friend functions in C++ have objects as arguments
 We can declare a friend function either in the private or public part
 The member names are not directly accessible to a friend function, and it has to use
the dot membership operator and object name with the member name
26

#include <iostream>
using namespace std;
class sample
{
private:
int x, y;
public:
void getdata ()
{
cout << "Enter values";
cin >> x >> y;
cout << "Values:" << x << "," << y << endl;
}
friend void sum(sample s);
};

Void sum(sample s)
{
int add = s.x + s.y;
cout << "sum is:" << add;
}

int main ()
{
sample s;
27

s.getdata();
sum(s);
return 0;
}

You might also like