FUNCTIONS IN CPP | LEARNING CPP ONLINE

What is the C++ function?

A function in C++ is a designated section of code that carries out a certain activity. It is a key building component of C++ programming that aids in grouping together unwieldy pieces of code into manageable chunks. A program can be divided into smaller, more manageable components using functions, which makes it simpler to comprehend, test, and maintain.

A function declaration and a function definition make up most functions in C++. The function definition contains the actual code that is performed when the function is called, whereas the function declaration specifies the function's name, return type, and optional parameters.

Here is a straightforward C++ function declaration and definition example:


In this example, the function is named and numbers and it takes two integer parameters a and b. It returns an integer value, which is the sum of the two input parameters. The function definition contains the code that performs the addition and returns the result.

To use this function, you would call it from another part of your program, passing the required arguments, and receive the result:


After executing this statement, the variable result would hold the value 8, which is the sum of 5 and 3.

If a function doesn't need to return a value, it can alternatively be defined without a return type (void). They may have many kinds of parameters or none at all.

With the help of C++ functions, you may reuse code, make it easier to maintain, and break up the logic of your programs into logical chunks for better organization and comprehension.

Why do we use the function?

A crucial component of computer languages like C++ is functions. Use functions in your code for the following reasons:

  • Code reuse is made possible via functions, which let you write a block of code just once and use it repeatedly throughout your program. Instead of repeatedly creating the same code, you can quickly accomplish a certain action by encapsulating it into a function that can be called whenever you need to. This encourages code uniformity, saves time and effort, and lessens the likelihood of introducing errors.
  • Functions aid in the modularization of a program by dividing it into smaller, stand-alone components. The code is more organized and simpler to handle when each function is in charge of a certain task or functionality. Consider functions as modular pieces that can be used to build intricate programs. This modular approach improves the readability, maintainability, and debuggability of the code.
  • Abstraction: By obscuring the specifics of a task's implementation, functions offer a certain level of abstraction. You simply need to be aware of a function's purpose and usage while using it; you don't need to understand how it is internally implemented. This abstraction makes programming easier and frees you up to concentrate on your program's high-level logic rather than becoming mired down in the low-level implementation details.
  • Code Readability: Functions help the code be easier to read and comprehend. You can convey the goal or usefulness of the code contained in a function by giving it a name that makes sense. This makes the code more readable and makes it simpler for you to grasp the code's purpose as well as that of others.
  • Testing and Debugging: Functions facilitate testing and troubleshooting. It is simpler to find and resolve problems since functions isolate particular jobs so that you can test and debug each one separately. This modular strategy aids in problem isolation and lowers troubleshooting complexity.
  • Scalability and Maintainability: Functions help your codebase be scalable and maintainable. Functions enable you to control complexity as your program expands by breaking it down into more manageable parts. Instead of searching and altering the entire codebase, you simply need to edit the relevant function if you need to enhance or extend a certain capability. This lessens the chance of making errors during revisions and enhances the maintainability of the code.
Briefly put, C++ functions provide code reuse, modularity, abstraction, better code readability, simpler testing and debugging, and scalability and maintainability. They are an effective tool for structuring, managing, and organizing your code, which results in more robust and effective programs.

Types of function

In C++, functions can be divided into a number of kinds according to their usage and properties. Here are a few typical kinds of functions:

  • Build-in function: Functions that are built into the C++ programming language are known as built-in functions. Since they are a component of the standard library, you can use them right away in your code without having to implement them further. Printf(), scanf(), sqrt(), and strlen() are a few examples. Common operations and activities are provided by these functions.
  • User-defined Functions: These are functions that the programmer defines to carry out particular activities as required by the program. To modularize code, increase reusability, and simplify code organization, programmers construct user-defined functions. To meet the needs of your program, you can build functions with a variety of return types, input arguments, and functionality.
  • Recursive function: Functions that repeatedly call themselves are referred to as recursive functions. By segmenting a problem into smaller subproblems and resolving each one in turn, they are able to solve it until they reach the base case. For instance, calculating factorials, locating Fibonacci numbers, and navigating tree structures are all examples of issues that can be solved with recursive functions.
  • Inline function: Inline functions are functions that the compiler expands at the point of call rather than being called as a separate function. Because function call overhead is decreased, performance may be enhanced. Before the function definition, the inline keyword can be used to specify an inline function.
  • Function Templates: You can build general functions that can operate on various data types by using function templates. They give you a mechanism to define a single function definition that you can use with a variety of types, allowing you flexibility and code reuse. The template keyword is used to define function templates, and they can include one or more template arguments.
  • Constructor Functions: When an object of a class is formed in C++, a special function known as a constructor is called. They carry out any required setup actions as well as initialize the object's data members. Constructors do not provide a return type and have the same name as the class. They can be overloaded to give the class several initialization options.
  • Destructor function: Destructor functions are unique procedures that are called whenever an object of a class is destroyed or exits its scope. Any resources that the object accumulated throughout its lifetime must be cleaned up by them. There are no parameters or return types in destructors, which have the same name as the class and are followed by a tilde ().

Built-in function

The C++ standard library provides built-in functions, also referred to as library functions. Without the need for additional code, these functions are already implemented and may be used in your C++ programs. Here are a few instances of built-in features:

cout and cin from the <iostream> library are used for console input and output.

1. Functions for input and output

Console input and output are handled by the <iostream> library's functions cout and cin.


2. Functions in mathematics:

The <cmath> library's sqrt() function determines a number's square root.


3. String operations

The <cstring> library's strlen() function returns the length of a string.


4. Characteristic Purposes

The <cctype> library's isalpha() function determines whether a character is an alphabet letter.


These are but a handful of instances of C++'s built-in functions. Mathematical computations, string manipulation, file handling, memory management, and other operations are all available through the C++ standard library. To streamline coding duties and make use of pre-existing functionality, you can incorporate the proper header files and use these functions in your programmers’.

User-define function

A function written by the programmer to carry out a particular duty within the software is known as a user-defined function. You can use it to organise code better, increase reusability, and modularize it. Depending on the needs of the programme, user-written functions might have a variety of return types, parameters, and functionality. They are defined by the programmer. Following are a few illustrations of user-defined functions:

  • Addition function: 

The addNumbers() function is defined in this example to compute the sum of two numbers. It executes the addition operation on two integer arguments, a and b, and then returns the outcome.

  • Factorial function:

To determine the factorial of a number, the factorial() function is defined in this example. A base case is eventually found after using recursion to divide the problem into smaller subproblems.
  • Print message function:

The printMessage() function is defined in this example to print a straightforward message. It serves only to encapsulate the printing mechanism and has no parameters or return value.

These are only a few illustrations of C++ user-defined functions. Depending on the particular needs of your program, user-defined functions can have a variety of structures and functionalities. They let you encapsulate functionality, make your code easier to comprehend, and encourage code reuse.

Recursive function

A function that calls itself within its own body is said to be recursive. Programmers can utilize this potent strategy to solve issues that can be divided into smaller issues. Recursive functions often have a base case that specifies when they should stop calling themselves. They operate by breaking down the original problem into smaller and easier subproblems until the base case is reached. A recursive function is demonstrated here:



The factorial of an integer n is calculated in this example via the recursive function factorial(). When n is equal to 0 or 1, which happens in the base case, the function just returns 1. The function calls itself with the argument n - 1 and multiplies it by n for any other value of n. Recursively, this process goes on until the base case is reached.

By repeatedly calling factorial() with decreasing numbers, the program divides the problem into smaller subproblems when it runs factorial(5): factorial(5) call factorial(4), which calls factorial(3), and so on until it reaches the base case. Once the base case is reached, the recursion begins to unwind, multiplying the results at each stage until the desired outcome is realized.

The output of the program would be:


Recursive functions come in handy when dealing with issues that have recurring patterns and can be broken down into more manageable sub-issues that are all exactly the same. To prevent infinite recursion, the recursive function must have an appropriate base case and termination condition.

Inline function

An "inline function" is a programming concept that allows the compiler to insert the function's code right away at the time the function is invoked rather than producing a separate function call. This can improve performance by removing the overhead of function calls.

The following C++ example will demonstrate how inline functions work:


In this illustration, we defined an inline square function that computes the square of a number. The compiler substitutes the function call with the actual function code when the square function is called in the main function. This indicates that the code that was executed resulted in = x * x;.

When a function is small and the performance impact of function calls would be obvious, it can be advantageous to use inline functions. It's crucial to remember that the compiler ultimately decides whether or not to inline a function, and the inline keyword only serves as a hint to the compiler. The inline keyword need not always be used explicitly because modern compilers may frequently perform optimizations automatically.

Function template

In C++, you can build generic functions that work with many data types without having to write several function definitions. Templates allow for code reuse and flexibility when building algorithms or operations that may be applied to several types.


In this instance, we've defined a maximum function template. The generic type represented by the template parameter T will be chosen when the function is invoked. The greater value is returned by the function after comparing two values of type T.

To determine the maximum of several kinds in the main function, we use the maximum function template. With two integers, two doubles, and two characters, we call maximum. The proper versions of each function are created by the compiler automatically depending on the data type.

When the code is compiled, the compiler generates the following function instantiations:


The code demonstrates how the same function template may be used with several data types, enabling code reuse and obviating the need to write separate versions of the function for each data type.

Keep in mind that function templates can potentially include numerous template arguments, enabling more flexible generic functions.

Constructor function

When an object belonging to a class is formed, a constructor, which is a special member function of the class or struct, is automatically called. The initial state of the object is built up in the constructor, which is also used to initialize the class's data members. In other words, constructors offer a method for creating and initializing class objects.

A C++ example is provided below to demonstrate constructor functions:


In this illustration, the rectangular form is represented by the class named rectangular. There are two constructors for the Rectangle class: a parameterized constructor and a default constructor.

When creating an object without any arguments, Rectangle(), the default constructor, is invoked. In this instance, the rectangle's width and height are both set to 0. When we build the defaulted object, the default constructor is used.

Rectangle(int w, int h) is a parameterized constructor that accepts two integer inputs to indicate the rectangle's width and height. It sets the supplied values as the initial values for the width and height data elements. When we create the paramRect object with dimensions 4 and 5, the parameterized constructor is called.

We call the calculateArea() member method to determine the rectangle's area after constructing the paramRect object and save the result in the area variable. The calculated area is then printed to the console.

The usage of constructors helps to guarantee that objects are correctly initialized and prepared for use at the time of creation. They are essential to object-oriented programming because they offer a mechanism to establish an object's initial state.

Destructor Functions:

A destructor is a particular member function of a class or struct in programming that is invoked whenever an object of that class is destroyed or exits its scope. Before an object is deleted from memory, resources that were allocated by it are cleaned up using destructors. They are the opposite of constructors, which set an object's state in motion.

A C++ example is provided below to demonstrate Destructor functions:


In this illustration, a class named Resource stands in for a resource that must be appropriately acquired and released. There are constructors and destructors for the class.

When an object of the Resource class is created, the constructor, specified as Resource(), is immediately called. In this instance, it prints "Resource acquired."

When an object is destroyed or leaves the scope of the application, the destructor, defined as Resource(), is immediately called. In this instance, it displays the text "Resource released."

We construct an object of the Resource class called a resource in the main method. The constructor is automatically invoked and prints the phrase "Resource acquired" when the object is constructed.

A nested object called nested resource is created within a code block. The message "Resource released" is written when the nested object exits the scope at the conclusion of the code block, and its destructor is automatically called.

The resource object finally leaves the scope after the main function completes, and its destructor is automatically executed, outputting the phrase "Resource released."

Prior to an object being destroyed, destructors are employed to carry out any necessary cleanup procedures, such as allocating dynamic memory, shutting files, or freeing up other resources. As a result, resource leaks are avoided and the program's general correctness is maintained. They make sure that the object's resources are appropriately handled and released.

No comments:

Post a Comment