Programming with Functions in C++ and Python

Programming with Functions in C++ and Python

- A blog by Prathiksha Kini

Introduction:

A function is a block of code that is used to perform a particular task. It is used to reuse the code and avoid repetition. Functions enable the programmers to break down or decompose a problem into smaller chunks each of which performs a particular task.

Functions are not something that we use commonly in programming. It is something that we all experience and visualize in our everyday life. Let me give you a simple example to understand the concept very well. I hope you might have photocopied your notes or taken printouts of some document at one or the other time in your life. Have you ever wondered how the printing machine works? Well! You might have observed that the printer accepts a piece of paper from the bundle passes that paper into the roller of the printing machine and then finally gives the printed paper as the output. So this series of steps that a printing machine takes to print a paper is basically a sort of function and it performs these steps repetitively to print a bunch of papers from the bundle.

I hope this explanation adds some sense to your understanding of functions. So let’s quickly deep dive into what functions in programming languages like C++ and Python. Though they are similar to the example I have cited above we need to describe these processes of activities with the help of a code so that they can be analyzed and interpreted by our computer system.

Before I begin my discussion, here are a few points to be noted:

  1. In this module we will be concentrating on functions, syntax, and its types in C++ and Python.

  2. There are no prerequisites to take up this module. I suggest using any good programming editor preferably Visual Studio Code which allows you to write code in either of these languages and is beginner friendly.

  3. The module is designed in such a way that it’s easy to comprehend for anyone irrespective of their prior knowledge of coding. All the topics will be covered from the very basic and I trust you that by the end of this module you will be able to master functions in C++ and Python.

So without further ado let’s start exploring functions in C++.

There are 2 types of functions in C++:

They are User-defined functions and Built-in Functions

  1. Built-in Functions: These are the type of functions that are already defined in the programming library. Ex: pow(), min(), max(), sum(), binary_search(), lower_bound(), sqrt() and many more. They can be used by simply importing the appropriate header files. It must be noted that the main function in C++ is also a type of inbuilt function which is used as an entry point to the execution of any C++ program.

  2. User-defined functions: The functions which are defined by the user to customize to his own needs are called User-defined functions.

Note: The functions will be executed only if there is a call to that function.

Syntax of a User defined function in C++

return_type function_name(parameter list ) {
   body of the function
}

Well! This might seem a bit weird and complicated at first glance. Do not worry let’s break down the syntax into simple components and analyze its functionality of it!

  1. return_type is a built-in keyword (reserved word) in C++ which indicates the type of value you want the function to return. The return_type can be int, void, double, bool, long double, float, etc. The void data type is used if you don’t want to return any value from the calling function whereas int, float, double, and bool are used if you want to return an integer, float, double or boolean value from the calling function.

  2. function_name is a user-defined function name for the calling function. You can write any function name of your choice but programmatically it's always a good practice to assign meaningful function names. Suppose you want to perform the addition of two numbers its a good practice to use the function name as a sum or add instead of using any other names.

  3. parameter list is like a placeholder. When a function is invoked you pass a value to the parameter. The parameter list refers to the type, order, and number of the parameters of a function. Parameters are optional. It’s not necessary to have a parameter for a function.

  4. Function body is like the heart of your function where you define the logic of your program using different programming constructs.

There are 3 main parts to declaring and defining a function: (Prototyping a function)

  1. Function declaration: A function declaration tells the compiler about a function name and how to call the function.

  2. Function definition: A section where you define your function and write the actual programming logic

  3. Function call: 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. This is the step where the function is triggered.

A simple example demonstrating a function in C++

//Function declaration
void sum(int,int);  

//Function definition
void sum(int a,int b){
   cout<<"Sum= "<<a+b<<endl;
}

//Function call
sum(a,b);

Based on the number of parameters and return type there are 4 types of functions in C++:


Functions with no arguments and no return type:

These are the type of functions that do not accept any parameter as the argument and do not return any value. So the return type of such function is void.

// Function Declaration - no argument and no return value 
void function();

Functions with arguments and no return type:

These types of functions accept parameters as the arguments but do not return any value.

// Function Declaration - argument but no return value
void function3(int a,int b);

Functions with no arguments and return type:

These functions accept no parameters but return an integer, boolean or floating field value to the calling function.

// Function Declaration - no argument but return value 
  int function2();

Functions with arguments and return type:

These functions accept parameters and return an integer, boolean or floating field value to the calling function.

// Function Declaration - argument but return value
   int function4(int a,int b);

I believe you are familiar with the basics of functions in C++. So let’s step ahead by learning advanced concepts of functions!

There are two ways to pass value or data to a function in C++ language:

  1. Call By Value: The call by value method of passing arguments to a function copies the actual value of an argument into the formal parameter of the function. In this case, changes made to the parameter inside the function have no effect on the argument. By default, C++ uses call-by-value to pass arguments.

  2. Call By reference: The call by reference method of passing arguments to a function copies the address of an argument into the formal parameter. It means the changes made to the parameter affect the passed argument.

To make it easy to understand refer to this animation pasted below!

l4aptnsmawrur69mpixf.gif

Inline functions in C++

The inline function is an enhancement feature in C++. An inline function needs to append the inline keyword before the function and looks like the normal function. But at the compile time Compiler replaces the function definition of the inline function instead of calling the function definition at the runtime. However excessive use of inline functions leads to the degradation of the performance of the program.

It’s a suggestion to the compiler to make it inline and the compiler checks for the following conditions:

  1. The function should not contain switch, loop, or goto statements.
  2. The function should not contain any static variables (A static variable is a variable that is declared using the keyword static. The space for the static variable is allocated only one time and this is used for the entirety of the program)
  3. The function should not be big
  4. The function should not be recursive
  5. The function should not return anything or the return type should be void.

Syntax of Inline functions:

inline return_type function_name( param_1,param_2 ... param_n ) {
 //inline function body
 }

Advantages of inline functions:

  1. It speeds up the function call by reducing the overhead calls of the function.
  2. Increases the performance of the program.
  3. Push or pop in a stack doesn’t happen in a function if there are no overhead calls. Disadvantages of inline functions:
  4. It increases cache results and hence leads to poor execution of the program.
  5. The size of the executable file increases as the code is expanded.
  6. When the program code is changed it is necessary to recompile the program before executing.

Function Overloading:

Function overloading is one of the 7 different Object-oriented programming features of C++. Going through the standard definition function overloading can be defined as a feature of object-oriented programming where two or more functions can have the same name but different parameters. It is a type of compile time polymorphism. Here are some examples of function overloading. Note: Multiple functions can have the same name as long as their return type or function parameters are different.

int function(int x)
float function(float x)
double function(double x, double y)

Function Overriding:

When the base class and derived class have member functions with exactly the same name, same return type, and same arguments list, then it is said to be function overriding. It helps us in achieving run-time polymorphism. Here is an example that depicts function-overriding:

public class Base{
  access_modifier:
    // overridden function
    return_type function_name(){}
  };
}
  public class Derived : public Base {
    access_modifier:
      // overriding function
      return_type function_name(){}
    };
  }

Default arguments in C++:

A default argument is a value provided in a function declaration that is automatically assigned by the compiler if the calling function doesn't provide a value for the argument. It must be noted that initialization of the parameters is done from right to left.

#include <iostream>
using namespace std;
int sum(int a, int b=10, int c=20);
int main(){
   cout<<sum(1)<<endl;
   cout<<sum(1, 2)<<endl;
   cout<<sum(1, 2, 3)<<endl;
   return 0;
}
int sum(int a, int b, int c){
   int z;
   z = a+b+c;
   return z;
}

Friend Functions:

A friend function in C++ is defined as a function that can access private, protected, and public members of a class. The friend function is declared using the friend keyword inside the body of the class. Since friend functions can access the private data of members of other classes hence we can say that C++ is not a pure object-oriented language, unlike Java.

Syntax:

class className {
    ... .. ...
    friend returnType functionName(arguments);
    ... .. ...
}

Virtual Functions in C++:

A virtual function is a type of run-time polymorphism. It can be defined as a member function in the base class that you redefine in a derived class. It is declared using the virtual keyword.

Rules for writing virtual functions:

  1. It needs to be a member of some class.
  2. They cannot be static members
  3. They are accessed with the help of base pointers.
  4. We cannot have a virtual constructor but we can have a virtual destructor.
  5. They can be a friend of another class.

A virtual function in C++ helps ensure you call the correct function via a reference or pointer. The C++ programming language allows you only to use a single pointer to refer to all the derived class objects.

Example of virtual function:

#include <iostream>   
using namespace std; 

class A:
{    
 public:    
 virtual void display()    
 {    
  cout << "Base class is invoked"<<endl;    
 }    
};    
class B:public A    
{    
 public:    
 void display()    
 {    
  cout << "Derived Class is invoked"<<endl;    
 }    
};    
int main()    
{    
 A* a;    //pointer of base class    
 B b;     //object of derived class    
 a = &b;    
 a->display();   //Late Binding occurs    
}

Pure Virtual Functions:

A pure virtual function is a function declared in the base class that has no definition relative to the base class. A class containing a pure virtual function is called an abstract class. They are used for inheritance. It can be defined as

virtual void display() = 0;

Functions in Python Programming language!

Let’s start our journey by creating a simple function in Python

Creating function:

In Python, a function is defined using the def keyword:

def my_function(): 
      print("Hello from a function")

Note: Indentation of a function body must be maintained whenever you write functions!

Calling a function:

Calling a function in python similar to the function call in C++.

my_function()

Congratulations! On writing your first function in Python.

Passing Arguments:

def my_function(fname):
      print( " Hello :" +fname)
my_function("Rohit")
my_function("Rahul")


 def my_function(fname, lname):
         print(fname + " " + lname) 
 my_function("Rishab", "Pant")

Return Values:

To let a function return a value, use the return statement:

Example:

def my_function(x): 
       return 5 * x 
print(my_function(3)) 
print(my_function(5)) 
print(my_function(9))
#Python function to calculate the sum of two variables
 #defining the function 
def sum (a,b): 
     return a+b;
 #taking values from the user
 a = int(input("Enter a: ")) 
b = int(input("Enter b: ")) 
#printing the sum of a and b 
print("Sum = ",sum(a,b)

Required Arguments:

Till now, we have learned about function calling in Python. However, we can provide the arguments at the time of the function call. As far as the required arguments are concerned, these are the arguments that are required to be passed at the time of function calling with the exact match of their positions in the function call and function definition. If either of the arguments is not provided in the function call, or the position of the arguments is changed, the Python interpreter will show the error.

#the function calculates returns the sum of two arguments a and b
 def calculate(a,b):
        return a+b
 calculate(10) # this causes an error as we are missing the required arguments b.

Default Arguments

Python allows us to initialize the arguments at the function definition. If the value of any of the arguments is not provided at the time of the function call, then that argument can be initialized with the value given in the definition even if the argument is not specified at the function call.

def printme(name,age=22): 
        print("My name is",name,"and age is",age) 
 printme(name = "john")

The self parameter in Python:

Self represents the instance of the class. By using the “self” we can access the attributes and methods of the class in python. It binds the attributes with the given arguments. It is used to initialize the members of the class. There is a special member function called init which takes self as the parameter and initialized the members of the class upon the creation of the object.

class Person:
  def __init__(self, name, age):
      self.name = name
      self.age = age

  def myfunc(abc):
    print("Hello my name is " + abc.name)

p1 = Person("John", 36)
p1.myfunc()

Arbitrary Arguments:

args If you do not know how many arguments will be passed into your function, add a before the parameter name in the function definition. This way the function will receive a tuple of arguments, and can access the items accordingly: Example If the number of arguments is unknown, add a * before the parameter name:

def my_function(*ks):
         print("The your favorite IPL team is " + ks[2]) 
my_function("RCB", "MI", "CSK")

Keyword Arguments:

You can also send arguments with the key = value syntax. This way the order of the arguments does not matter. Example:

def my_function(s1, s2, s3): 
          print("Value " + s3) 
my_function(s1 = "C", s2 = "C++", s3 = "Python")

So that’s all you need to know about functions in C++ and Python! Happy learning :)