Module 2
Module 2
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.
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
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
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: 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
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’.
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.
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
Declaration of a class
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.
(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
// Header Files
#include <iostream>
#include<conio.h>
public:
void read() {
cout << "Enter Name :";
cin >> name;
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
cout << "Read and Print Student Information Class Example Program In C++\n";
Sample Output
70
Name :Operas
Registration Number :10002
Marks :95 , 85 , 70
Total :250
Average :83.3333
#include <iostream>
using namespace std;
class Room {
private:
double length;
double breadth;
double height;
public:
double calculateArea() {
return length * breadth;
}
double calculateVolume() {
19
int main() {
return 0;
}
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
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
#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();
}
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;
}