1. Shri Shivaji Science College, Amravati
Department of Computer Science
Topic- Introduction of Object Oriented
Programming
Prepared By
Dr. Ujwala S. Junghare
Assistant Professor
Dept. of Computer Science
2. • Introduction
• Types of Functions
• return Statement
• Call by Value
• Default Argument
• Inline Function
• Recursion
3. Definition : (Function)
“A self contained block of statements having its
own name and used to perform a specific task is called as
Function.”
Each and every function has some attributes listed
below:
1. Any identifier followed by ( ) is the function in a program.
2. Each function has its own name.
3. Each function returns a value.
4. Each function has its return type.
5. Each function has specific number of arguments of specific
types that it can accept an process.
6. Each function as its own set of instructions called Body of
the function.
4. Types of Function:
The function in C++ are classified into basic
TWO types:
1. Library Functions(Built-in)
2. User Defined Functions.
1. Library Functions(Built-in):
The function whose name, return type,
arguments and body(Code) is already defined by C++ language
itself is called as Library Function of C++.
NOTE: All library functions of C++ are defined in header files.
For example,
1. sqrt() is defined in math.h
2. strlen() is defined in string.h
5. 2. User Defined Functions:
“The function whose name, return type,
arguments and body(Code) is defined externally by
programmer is called as User-Defined function.”
• Whenever we want to use a user defined function in program,
we have to perform the following THREE operations in
program.
1. Defining function
2. Function Prototype
3. Invoking a function
6. The code of the function defined with following
syntax in a program is called Function Definition.
Syntax:
• The ‘argument list’ contains the variable declarations
separated with commas.
• These arguments are called as FORMAL PARAMETERS of
the function.
return_type func_name(argument list)
{
// Executable statements
// return statement
}
7. For example,
void add(int x, int y) //x and y are FORMAL parameters
{
int z;
z=x+y;
cout<<“Addition=“<<z;
}
8. The function that is defined in program must be
declared first, either above the main() or inside the main() at the
beginning. This function declaration is called Function
Prototype.
Syntax:
For example,
void add(int, int);
The above statement declares function with name
‘add’ having return type ‘void’ and can accept two arguments of
type ‘int’.
NOTE: Default return type of function is ‘int’
return_type func_name(list of arguments type);
9. • To execute a function defined in a program we must invoke it
by using function calling statement as follows:
Syntax:
The ‘argument list’ contains expressions(variables or data
values) separated with commas. These arguments are passed
to the function are called as ACTUAL PARAMETERS.
For example,
void main()
{
int a=10;
add(a,20); // Invokes function ‘add’
}
NOTE: The value of ‘a’ and 20 are called actual parameters.
variable_name= func_name(argument list);
10. Each and every function in C++ should return one and only
one value.
A function returns a value using ‘return’ statement provided
in C++. ‘return’ is the keyword of C++.
Hence, every function definition contains a ‘return’
statement at the end.
A ‘return’ statement in body of the function does TWO tasks:
1. Returns the value to the calling function.
2. Transfers the control of execution to the calling
function.
Syntax:
NOTE: A ‘return’ statement can return only one value.
return expr;
11. For example:
int add(int,int); // Function Prototype
void main()
{
int a=10;
int b=20;
int c;
c=add(a,b); // Function Calling Statement
cout<<“Result of addition=”<<c;
}
int add(int x,int y) // Function Definition
{
int z;
z=x+y;
return(z); // ‘return’ stmt
}
12. We can call/invoke a function from any other function.
While calling a function you are passing value/variable name
as actual parameter then it is called Call By Value method.
In this method, we can’t make changes in the values of
actual parameters in called function.
Rather, we can apply changes on the copies(Xerox) of the
actual parameters only.
13. C++ allows us to call a function without passing all of its
arguments.
It is possible by initializing a value to such a argument in
function declaration.
Such argument to which value is assigned is called as Default
Argument of the function.
For example,
void add(int x, int y=100, int z=200);
Here, ‘y’ and ‘z’ are default arguments of the function add().
We can call the function by passing only one value also.
14. Passing and Returning Objects in C++
In C++ we can pass class’s objects as arguments and also return them from a
function the same way we pass and return other variables. No special keyword
or header file is required to do so.
Passing an Object as argument
To pass an object as an argument we write the object name as the argument
while calling the function the same way we do it for other variables.
Syntax:
function_name(object_name);
Example: In this Example there is a class which has an integer variable ‘a’ and
a function ‘add’ which takes an object as argument. The function is called by
one object and takes another as an argument. Inside the function, the integer
value of the argument object is added to that on which the ‘add’ function is
called. In this method, we can pass objects as an argument and alter them.
15. #include <iostream>
using namespace std;
class A
{ public:
int n=100;
char ch='A’;
void disp(A a)
{
cout<<a.n<<endl;
cout<<a.ch<<endl;
}
};
int main()
{
A obj;
obj.disp(obj);
return 0;
}
16. #include <bits/stdc++.h>
using namespace std;
class Example {
public:
int a;
// This function will take an object as an argument
void add(Example E)
{
a = a + E.a;
}
};
/ Driver Code
int main()
{
// Create objects
Example E1, E2;
// Values are initialized for both objects
E1.a = 50;
E2.a = 100;
cout << "Initial Values n";
cout << "Value of object 1: " << E1.a
<< "n& object 2: " << E2.a
<< "nn";
// Passing object as an argument to function add()
E2.add(E1);
// Changed values after passing object as argument
cout << "New values n";
cout << "Value of object 1: " << E1.a
<< "n& object 2: " << E2.a
<< "nn“;
return 0;
}
18. Returning Object as argument
Syntax:
object = return object_name;
Example: In the above example we can see that the add function does not return any
value since its return-type is void. In the following program the add function returns an
object of type ‘Example'(i.e., class name) whose value is stored in E3.
In this example, we can see both the things that are how we can pass the objects as well
as return them. When the object E3 calls the add function it passes the other two objects
namely E1 & E2 as arguments. Inside the function, another object is declared which
calculates the sum of all the three variables and returns it to E3.
This code and the above code is almost the same, the only difference is that this time the
add function returns an object whose value is stored in another object of the same class
‘Example’ E3. Here the value of E1 is displayed by object1, the value of E2 by object2
and value of E3 by object3.
19. // C++ program to show passing of objects to a function
#include <bits/stdc++.h>
using namespace std;
class Example {
public:
int a;
// This function will take object as arguments and return object
Example add(Example Ea, Example Eb)
{
Example Ec;
Ec.a = 50;
Ec.a = Ec.a + Ea.a + Eb.a;
// returning the object
return Ec;
}
};
int main()
{
Example E1, E2, E3;
E1.a = 50;
E2.a = 100;
E3.a = 0;
cout << "Initial Values n";
cout << "Value of object 1: " << E1.a
<< ", nobject 2: " << E2.a
<< ", nobject 3: " << E3.a
<< "n";
// Passing object as an argument to function add()
E3 = E3.add(E1, E2);
// Changed values after passing object as an argument
cout << "New values n";
cout << "Value of object 1: " << E1.a
<< ", nobject 2: " << E2.a
<< ", nobject 3: " << E3.a
<< "n";
return 0;
}
20. When value is not passed to such argument, then function
assigns the default value i.e. assigned value to the parameter.
It is also possible to pass value to such argument, at such a
situation function will assign the value passed to the
argument instead of its default value.
Note, that default arguments of the function must be trailing
arguments of the function.
21. When we call a function, then the control of the execution
transfers to the function, the body of the function is executed
and then control of execution returned to the calling
function.
This process is very time consuming.
Hence, C++ allows us to define a function to which control is
not transferred instead body of that function is substituted at
function calling statement called expansion.
Such function is called as Inline Function.
In C++, we can use inline function by placing ‘inline’
keyword in function definition.
inline retype fname(parameter list)
{
Body of the function
}
22. Rules for using Inline Functions:
1. It should not contain loop, switch or goto statement.
2. It should not contain static variables.
3. It should not be recursive function.
4. It should be defined before the calling function.
5. No prototype is required.
23. Function overloading is a C++ programming feature that allows us to
have more than one function having same name but different
parameter list.
In function overloading, the function can be redefined either by using
different types of arguments or a different number of arguments
according to the requirement. It is only through these differences
compiler can differentiate between the two overloaded functions.
For example the parameters list of a function myfuncn(int a, float b) is
(int, float) which is different from the function myfuncn(float a, int b)
parameter list (float, int).
Function overloading is a compile-time polymorphism.
Function overloading
24. For example:
sum(int num1, int num2)
sum(double num1, double num2)
These two functions have different parameter type
sum(int num1, int num2)
sum(int num1, int num2, int num3)
These two have different number of parameters.
sum(int num1, double num2)
sum(double num1, int num2)
These two have different sequence of parameters.
25. #include <iostream>
using namespace std;
class Addition
{
public:
int sum(int num1,int num2)
{ return num1+num2;
}
int sum(int num1,int num2, int num3)
{ return num1+num2+num3;
}
};
int main(void)
{
Addition obj;
cout<<obj.sum(20, 15)<<endl;
cout<<obj.sum(81, 100, 10);
return 0;
}
26. #include <iostream>
using namespace std;
class DemoClass
{
public:
int demoFunction(int i)
{
return i;
}
double demoFunction(double d)
{ return d;
} };
int main(void)
{
DemoClass obj;
cout<<obj.demoFunction(100)<<endl;
cout<<obj.demoFunction(5005.516);
return 0;
}
27. Advantages of Function overloading:
The main advantage of function overloading is to the improve the code
readability and allows code reusability.
In the example 1, we have seen how we were able to have more than one
function for the same task(addition) with different parameters, this allowed us
to add two integer numbers as well as three integer numbers, if we wanted we
could have some more functions with same name and four or five arguments.
Imagine if we didn’t have function overloading, we either have the limitation to
add only two integers or we had to write different name functions for the same
task addition, this would reduce the code readability and reusability.
Disadvantages of function Overloading in C++
Function declarations that differ only by its return type cannot be overloaded
with function overloading process.
Member function declarations with the same parameters or the same name
types cannot be overloaded if any one of them is declared as a static member
function.
class XYZ{
static void func();
void func(); // error
};
28. Default Arguments
In C++ programming, we can provide default values for function parameters.
If a function with default arguments is called without passing arguments, then
the default parameters are used.
However, if arguments are passed while calling the function, the default
arguments are ignored.
29.
30. We can understand the working of default arguments from the image
above:
1.When temp() is called, both the default parameters are used by the
function.
2.When temp(6) is called, the first argument becomes 6 while the default
value is used for the second parameter.
3.When temp(6, -2.3) is called, both the default parameters are overridden,
resulting in i = 6 and f = -2.3.
4.When temp(3.4) is passed, the function behaves in an undesired way
because the second argument cannot be passed without passing the first
argument.
Therefore, 3.4 is passed as the first argument. Since the first argument has
been defined as int, the value that is actually passed is 3.
31. Inline function
C++ provides an inline functions to reduce the function call overhead. Inline
function is a function that is expanded in line when it is called.
When the inline function is called whole code of the inline function gets inserted
or substituted at the point of inline function call. This substitution is performed
by the C++ compiler at compile time. Inline function may increase efficiency if
it is small.
C++ inline function is powerful concept that is commonly used with classes. If a
function is inline, the compiler places a copy of the code of that function at each
point where the function is called at compile time.
Any change to an inline function could require all clients of the function to be
recompiled because compiler would need to replace all the code once again
otherwise it will continue with old functionality.
32. To inline a function, place the keyword inline before the function name and define the
function before any calls are made to the function. The compiler can ignore the inline
qualifier in case defined function is more than a line.
The syntax for defining the function inline is:
inline return-type function-name(parameters)
{
// function code
}
#include <iostream>
using namespace std;
inline int Max(int x, int y) {
return (x > y)? x : y;
}
// Main function for the program
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;
return 0;
}
33. Remember, inlining is only a request to the compiler, not a command.
Compiler can ignore the request for inlining. Compiler may not perform
inlining in such circumstances like:
1) If a function contains a loop. (for, while, do-while)
2) If a function contains static variables.
3) If a function is recursive.
4) If a function return type is other than void, and the return statement
doesn’t exist in function body.
5) If a function contains switch or goto statement.
34. Inline functions provide following advantages:
1) Function call overhead doesn’t occur.
2) It also saves the overhead of push/pop variables on the stack when
function is called.
3) It also saves overhead of a return call from a function.
4) When you inline a function, you may enable compiler to perform context
specific optimization on the body of function. Such optimizations are not
possible for normal function calls. Other optimizations can be obtained by
considering the flows of calling context and the called context.
5) Inline function may be useful (if it is small) for embedded systems
because inline can yield less code than the function call preamble and return.
Inline function disadvantages:
1) If you use too many inline functions then the size of the binary
executable file will be large, because of the duplication of same code.
2) Too much inlining can also reduce your instruction cache hit rate, thus
reducing the speed of instruction fetch from that of cache memory to that of
primary memory.
35. Friend Function
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.
Friend Function Like friend class, a friend function can be given special grant to
access private and protected members. A friend function can be:
a) A method of another class
b) A global function
A friend can be a function, function template, or member function, or a class or class
template, in which case the entire class and all of its members are friends.
A friend function can access the private and protected data of a class. We declare a
friend function using the friend keyword inside the body of the class.
class className {
... .. ...
friend returnType functionName(arguments);
... .. ...
}
36. To declare a function as a friend of a class, precede the function prototype in the
class definition with keyword friend as follows −
class Box {
double width;
public:
double length;
friend void printWidth( Box box );
void setWidth( double wid );
};
To declare a function as a friend of a class, precede the function prototype in the
class definition with keyword friend as follows −
class Box {
double width;
public:
double length;
friend void printWidth( Box box );
void setWidth( double wid );
};
37. To declare all member functions of class ClassTwo as friends of class ClassOne, place a following declaration in the
definition of class ClassOne −
friend class ClassTwo;
Consider the following program −
#include <iostream>
using namespace std;
class Box {
double width;
public:
friend void printWidth( Box box );
void setWidth( double wid );
};
// Member function definition
void Box::setWidth( double wid ) {
width = wid;
}
// Note: printWidth() is not a member function of any class.
void printWidth( Box box ) {
/* Because printWidth() is a friend of Box, it can
directly access any member of this class */
cout << "Width of box : " << box.width <<endl;
}
// Main function for the program
int main() {
Box box;
// set box width without member function
box.setWidth(10.0);
// Use friend function to print the wdith.
printWidth( box );
return 0;
}
38. 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.
39. Syntax:
class_name array_name [size] ;
Example:
#include <iostream>
class MyClass {
int x;
public:
void setX(int i) { x = i; }
int getX() { return x; }
};
void main()
{
MyClass obs[4];
int i;
for(i=0; i < 4; i++)
obs[i].setX(i);
for(i=0; i < 4; i++)
cout << "obs[" << i << "].getX(): " << obs[i].getX() << "n";
getch();
}
Output:
obs[0].getX(): 0
obs[1].getX(): 1
obs[2].getX(): 2
obs[3].getX(): 3
40. Pointer to objects:
‘this’ pointer:
Object can also have an address, so there is also a pointer that can point to the
address of an object. Such pointer is known as ‘this’ Pointer.
As soon as you define a class, the member functions are created and placed in the
memory space only once. That is, only one copy of member functions is maintained
that is shared by all the objects of the class. Only space for data members is
allocated separately for each object (See the following figure).
If member function 3 is capable of changing the value of data member2 and we
want to change the value of data member2 of object1. How could the member
function3 come to know which object's data member2 is to be changed ?
The answer to this problem is this pointer. When a member function is called, it
is automatically passed an implicit (in-built) argument that is a pointer to the
object that invoked the function. This pointer is called this.
41. To understand ‘this’ pointer, it is important to know how objects look at
functions and data members of a class.
Each object gets its own copy of the data member.
All-access the same function definition as present in the code segment.
Meaning each object gets its own copy of data members and all objects share a
single copy of member functions.
The ‘this’ pointer is passed as a hidden argument to all nonstatic member
function calls and is available as a local variable within the body of all non
static functions. ‘this’ pointer is not available in static member functions as
static member functions can be called without any object (with class name).
42. For a class X, the type of this pointer is ‘X* ‘. Also, if a member
function of X is declared as const, then the type of this pointer is ‘const
X *’
In the early version of C++ would let ‘this’ pointer to be changed; by
doing so a programmer could change which object a method was
working on. This feature was eventually removed, and now this in C++
is an r-value.
C++ lets object destroy themselves by calling the following code :
delete this;
As Stroustrup said ‘this’ could be the reference than the pointer, but the
reference was not present in the early version of C++. If ‘this’ is
implemented as a reference then, the above problem could be avoided
and it could be safer than the pointer.
Following are the situations where ‘this’ pointer is used:
43. 1) When local variable’s name is same as member’s name
#include<iostream>
using namespace std;
/* local variable is same as a member's name */
class Test
{
private:
int x;
public:
void setX (int x)
{
// The 'this' pointer is used to retrieve the object's x
// hidden by the local variable 'x'
this->x = x;
}
void print() { cout << "x = " << x << endl; }
};
int main()
{
Test obj;
int x = 20;
obj.setX(x);
obj.print();
return 0;
}
44. Definition: (Constructor)
“A function defined in a class whose name is same as that of the class name and
having no return type is called as Constructor of that class.”
For example, xyz.cpp
NOTE:
A constructor is used to initialize an object.
A constructor is invoked automatically when object of class is creating.
Constructors must be defined in ‘public’ section.
A constructor does not have return type.
A constructor cannot be invoked using object of the class.
A constructor is different from normal functions in following ways:
Constructor has same name as the class itself
A constructor is automatically called when an object is created.
If we do not specify a constructor, C++ compiler generates a default constructor for
us (expects no parameters and has an empty body).
In C++, constructors are classified into following THREE types:
1. Default Constructor
2. Parameterized Constructor
3. Copy Constructor
45. Types of Constructors
Default Constructors: Default constructor is the constructor which doesn’t take any argument. It has no
parameters.
// Cpp program to illustrate the concept of Constructors
#include <iostream>
using namespace std;
class construct
{
public:
int a, b;
// Default Constructor
construct()
{
a = 10;
b = 20;
}
};
int main()
{
// Default constructor called automatically when the object is created
construct c;
cout << "a: " << c.a << endl
<< "b: " << c.b;
return 1;
}
Note: Even if we do not define any constructor explicitly, the compiler will automatically provide a
default constructor implicitly.