C++ Programming Complete Tutorial.

C++ is a High-level, General-purpose, object-oriented programming language created by Bjarne Stroustrup. It is one of the most popular cross-platform programming languages for developing high-performance applications. 

C++ Complete Tutorial

In this tutorial, we will cover all the basics and advanced concepts of C++ programming language with lots of examples. As C++ is an Object Oriented Programming (OOPs) language so we will also cover concepts like Classes, Polymorphisms, Inheritance, Encapsulation, Friend functions, and more.


List of Topics: 

Introduction to Programming Languages.
C++ Program Basics
Introduction to C++ Programming.
Input/Output Stream in C++.
Using Namespace in C++.
Comments in C++ Programming.
Variables, Constant, and Literals in C++.
Escape Sequences in C++.
Data Types in C++.
Type Conversion in C++.
Signed and Unsigned Types in C++.
Operators in C++.
Flow Controls in C++.
if..else statement in C++.
For Loop in C++.
While Loop in C++.
do...while Loop in C++.
Break and Continue Statement in C++.
Switch Statement in C++.
Functions and Recursion in C++.
Functions in C++.
Types of Function in C++.
Call by Value and Call by Reference in C++.
Function Overloading in C++.
Recursion in C++.
Arrays and String in C++.
Introduction of Array in C++.
One-Dimensional Array in C++.
Two-Dimensional Array in C++.
Static and Dynamic Arrays.
How To Pass Array to Function in C++.
String in C++.
Character Array Vs String in C++.
String Member Functions in C++.
User Define Data Types in C++.
Structure in C++.
Union in C++.
The enumeration in C++.
Classes in C++.
Object Oriented Programming in C++.
Classes and Objects in C++.
Constructors and Destructors in C++.
Access Specifiers in C++.
Encapsulation in C++.
Inheritance in C++.
Polymorphism in C++.
Friend Function in C++.
Virtual Function in C++.

You can also learn C++ programming from our video lectures that are available on our YouTube channel AlgoLesson.

Pointers in C++

In C++ programming, a pointer is a variable that is used to store the address of another variable of the same type. They are very useful to pass the value as a reference in the function (also known as call by reference). It points to the memory location where the first byte of the object is stored.

Syntax for Declaration of Pointer Variable.

syntax: data_type * pointer_name;
example: int *ptr; 
//ptr can point to the address of a integer type variable


Working of Pointer in C++.

pointer in C++
Define a pointer variable and initialize the pointer variable with the address of variable using unary operator (& also called address of operator) which return the address of the variable.
int x = 5;
int *ptr;
ptr = &x; //assign address of variable x to the pointer variable ptr

The derefrence/indirected operator (*) is an operator that is used to access the value stored at the location pointed by the pointer. It return the value of the variable located at that address specified by the operand. Using * operator we can also change the value of the variable pointed by the pointer. 
int x = 5;
int *ptr = &x;

cout<<*ptr; //answer: 5

*ptr = 10;
cout<<*ptr; //answer: 10

Pointer Example Code:

//C++ Pointer Example
#include<iostream>
using namespace std;

int main(){

    //variable declaration
    int x = 10;
    //pointer vairbale declaration 
    int *ptr;
    //pointer variable initialize
    ptr = &x; 
    
    cout<<"Value of x: "<<x<<endl;
    cout<<"Value of *ptr: "<<*ptr<<endl;
    cout<<"Value of ptr: "<<ptr<<endl;

    return 0;
}
Output:
Value of x: 10
Value of *ptr: 10
Value of ptr: 0xd36fff8d4

Pointer Example in Function (Call by Reference).

//C++ Pointer Example for function
#include<iostream>
using namespace std;

//call by reference
void swapValue(int *x, int *y){
    *x = 30;
    *y = 10;
}
int main(){

    int m = 10, n = 30;
    //function call
    swapValue(&m, &n);

    cout<<"m = "<<m<<endl;
    cout<<"n = "<<n;

    return 0;
}
Output:
m = 30
n = 10

Pointer to Pointer in C++.

Pointer to pointer is a condition in which we store the address of one pointer into another pointer which point the address of actual variable. The pointer to pointer is declare using two derefrencing operator (**).
syntax: int **pptr; //pointer to pointer

Example:
//C++ Pointer to Pointer Example
#include<iostream>
using namespace std;

int main(){

   int value = 30;
   //taking address of value
   int *ptr = &value;
   //taking address of pointer ptr
   int **pptr = &ptr;

   cout<<"Value of value: "<<value<<endl;
   cout<<"Value of *ptr: "<<*ptr<<endl;
   cout<<"Value of **ptr: "<<**pptr<<endl;

   return 0;
}
Output:
Value of value: 30
Value of *ptr: 30
Value of **ptr: 30

Key points to note:
  • Never apply the indirected operator (*) to the uninitialized pointer. 
int *ptr;
cout<<*ptr; //undefined behaviour
  • Never assign value to an uninitialize pointer, it will lead to segmentation fault error.
int *ptr;
*ptr = 1; //Segmentation Fault (SIGSEGV)


Difference Between Call By Value and Call By Reference in C++

In C++ programming, there are two ways of passing value to the function: Call by Value or Call by Reference


Before going further into this topic, I will suggest you understand the difference between actual parameters and formal parameters. The actual parameters are those parameters that are passed to the function and formal parameters are those parameters that are received by the function.


Call by Value: Here the values of actual parameters will be copied to formal parameters and these two different parameters store values in different memory locations. Any changes made to the variable inside function are not going to reflect back to the actual parameter. 

Example:

//C++ Example of call by value
#include<iostream>
using namespace std;

//function definition
void update(int x, int y){

   x = 5;
   y = 40;
   cout<<"Values inside function call:"<<endl;
   cout<<"x = "<<x<<endl;
   cout<<"y = "<<y<<endl;
}
int main(){

    int x = 10, y = 20;    
    
    //function call
    update(x, y);
    cout<<"Values after function call:"<<endl;
    cout<<"x = "<<x<<endl;
    cout<<"y = "<<y<<endl; 

    return 0;
}
Output:
Values inside function call:
x = 5
y = 40
Values after function call:
x = 10
y = 20

call by value example

Here in the above code, we have updated the value of x and y inside the function but that is not affecting the value of our original variable x and y inside the main() function. It is happening because variables inside update() are local to the function and get destroyed later. 


Call by Reference: Here both actual and formal parameters refer to the same memory location. Therefore, any changes made to the formal parameters will get reflected in the actual parameters. 
In Call by Reference, instead of passing values to the function we are passing the memory addresses at which those values are stored using the address of operator (&). The parameters of function are pointers that is used to hold the address of another variable(alert-success)
Example:
//C++ Example of call by reference
#include<iostream>
using namespace std;

//function definition
void update(int *x, int *y){

   *x = 50;
   *y = 40;
   cout<<"Values inside function call:"<<endl;
   cout<<"x = "<<*x<<endl;
   cout<<"y = "<<*y<<endl;
}
int main(){

    int x = 10, y = 20;    
    
    //function call
    update(&x, &y);
    cout<<"Values after function call:"<<endl;
    cout<<"x = "<<x<<endl;
    cout<<"y = "<<y<<endl; 

    return 0;
}
Output:
Values inside function call:
x = 50
y = 40
Values after function call:
x = 50
y = 40

call by reference
Here in the above code, we are passing the address of the variable &x and &y to the function update() and the parameters of this function are pointers (*x and *y). A pointer is used to hold the address of another variable and you can fetch the value present at that particular address using dereference operator (*).  

Difference Between Call by Value and Call by Reference.

Call By Value Call By Reference
Copies of arguments are passed to the function. Changes to parameters inside the function do not affect the original values. References to the original arguments are passed to the function. Changes to parameters inside the function directly affect the original values.
Syntax: void functionName(int a, int b) Syntax: void functionName(int &a, int &b)
Changes inside the function do not affect the original variables. Changes inside the function directly affect the original variables.
May have a performance impact if large data structures are passed since copies are made. Typically more efficient as no copies are made, especially for large data structures.
// Call By Value Example
void swap(int x, int y) {
int temp = x; x = y;
y = temp;
}
int main() {
int a = 5, b = 10;
swap(a, b); cout << "a: " << a << ", b: " << b;
return 0;
}
// Call By Reference Example
void swap(int &x, int &y) {
int temp = x; x = y; y = temp;
}
int main() {
int a = 5, b = 10; swap(a, b); cout << "a: " << a << ", b: " << b;
return 0;
}


Read more:

Types of Functions in C++

In C++ programming, you can categorize functions into four different categories based on the arguments we are passing to the function and the return type of the function. These are:

  • Function with no argument and no return type value.
  • Function with argument but no return type value.
  • Function with no argument but with return type value.
  • Function with argument and with return type value.

1. Function with no argument and no return type value.

In this type of function, we do not pass any value while calling the function and no value is returned from the function as an output.

Example:

#include<iostream>
using namespace std;

//function with no argument and no return type
void sum(){

    int x = 10, y = 5, z = 8;
    int sum = x + y + z;
    cout<<"Total Sum = "<<sum;
}
int main(){
    //function call
    sum();

    return 0;
}
Output:
Total Sum = 23

Here in the above code, the sum() function is called inside main() without any arguments. The sum() function performs the summation of three variable x, y, and z, and print the answer. As the return type of sum() is void so no value is returned by the function.

2. Function with argument but no return type value.

In this type of function, we do pass values while calling the function but no value is returned from the function as an output.

Example:
#include<iostream>
using namespace std;

//function with argument but no return type
void sum(int x, int y, int z){

    int sum = x + y + z;
    cout<<"Total Sum = "<<sum;
}
int main(){
    int a = 10, b = 3, c = 9;
    //function call
sum(a, b, c); return 0; }
Output:
Total Sum = 22

Here in the above code, the sum() function is called inside main() with three arguments a, b, and c, and the sum() function performs the addition of the three values and prints the total sum. The return type of the function sum() is void so no value is returned by the function.

3. Function with no argument but with return type value.

In this type of function, we do not pass values while calling the function but some value is returned from the function as an output. 

Example:
#include<iostream>
using namespace std;

//function with no argument but return type
int sum(){

    int x = 10, y = 8, z = 15, sum;
    sum = x + y + z;
    return sum;
}
int main(){
        
    //function call
    int answer = sum();
    cout<<"Total Sum = "<<answer;
    return 0;
}
Output:
Total Sum = 33

Here in the above code, the sum() function is called inside the main() function with no arguments, and the sum() function perform the addition of value x, y, and z and return the sum value. 

4. Function with argument and with return type value.

In this type of function, we do pass values while calling the function and some value is returned from the function as an output. 

Example: 
#include<iostream>
using namespace std;

//function with argument and with return type
int sum(int x, int y){

    int sum;
    sum = x + y;
    return sum;
}
int main(){

    int m = 10, n = 20;    
    //function call
    int answer = sum(m , n);
    cout<<"Total Sum = "<<answer;
    return 0;
}
Output:
Total Sum = 30

Here in the above, the sum() is called inside main() with two arguments m and n, and sum() adds those two values and returns the value of sum which is an integer. type.

Based on your requirement and condition you can choose any method out of four to solve your problem.

Read next:

Difference between Argument and Parameter.

The two terms Parameters and Arguments are often used interchangeably while working on functions in programming but both the term have totally different meanings let's understand the difference between them.

Parameters

A Parameter is a variable in the declaration and definition of the function. The value of these variables is used inside the function to perform some computation on it and return us some output. The parameter is also known as Format Parameter.  

Example:
//C++ Example for Parameters
#include<iostream>
using namespace std;

//function definition
//x and y are two parameters
int add(int x, int y){
    return (x + y);
}
int main(){

    int m = 22, n = 8, sum;
    //function call
    sum = add(m, n);
    cout<<"SUM = "<<sum;

    return 0;
}
Output:
SUM = 30

Here add() function is defined with two parameters x and y and this function is used to perform addition of two numbers.

Arguments

Argument is a actual value of the parameter that gets passed to the function when the function is called.These values are passed to the function at the time of function call. They are also called as Actual Parameter.

Example:
//C++ Example for Arguments
#include<iostream>
using namespace std;

//function definition
int sub(int x, int y){
    return (x - y);
}
int main(){

    int m = 20, n = 8, diff;
    //function call
    //m and n are two arguments
    diff = sub(m, n);
    cout<<"Difference = "<<diff;

    return 0;
}
Output:
Difference = 12

Here sub() function is called with two argument value m and n and the task of this function is to perform the substraction of two numbers.


How To Fix Implicit Declaration of function Error?

In the previous post, we discussed functions in detail and here in this post, we are going to discuss one error that we often encounter while working with functions which is the "implicit declaration of function". 


The implicit declaration function error is encountered when you use (or call) the function before declaring or defining it. It is because the compiler has no information about that function at the time of calling it so the compiler implicitly assumes something about the function.

Example:

//C++ Implicit Declaration of function
#include<iostream>
using namespace std;

int main(){
    
    int m = 6, n = 8;
    //function call
    int greater = find(m, n);
    cout<<"Greater number is: "<<greater;

    return 0;
}
//function definition
int find(int x, int y){

    if(x < y){
        return y;
    }
    else{
        return x;
    }
}
Output:
../src/main.c:48:9: error: implicit declaration of function 'find' [-Werror=implicit-function-declaration]
         find();
Here the find() function is not declared before calling inside the main function and the definition of the function is written after the main function so when it is called inside the main function the compiler has no information about the find() function and gives us an error message. (alert-warning)

How Execution takes place in C++?

Before understanding the solution for the above error it is important to understand how execution takes place in C++ Programming. 

If you are familiar with C++ programming you must have heard that execution starts from the global function main() but it is partially correct. The compiler starts the execution of the program from the first statement and all statements are executed one by one from top to bottom. Even if you have defined any function before or after the main then also the flow of execution will remain the same, but the statements inside the function get executed only when that function is called. 

How to resolve Implicit Declaration of Function Error?

There are two ways to resolve this error:
  • If you define the function before the main function then you only have to define it and you don't have to separately declare or define it. 
Example:  
//C++ Example program to find greater
#include<iostream>
using namespace std;

//function definition before using it
int find(int x, int y){

    if(x < y){
        return y;
    }
    else{
        return x;
    }
}
int main(){
    
    int m = 6, n = 8;
    //function call
    int greater = find(m, n);
    cout<<"Greater number is: "<<greater;

    return 0;
}
Output:
Greater number is: 8

  • If you define a function after the main function then you have to put a matching declaration of that function before the main.
Example:

//C++ Example program to find greater
#include<iostream>
using namespace std;

//function declaration before using it
int find(int, int);

int main(){
    
    int m = 6, n = 8;
    //function call
    int greater = find(m, n);
    cout<<"Greater number is: "<<greater;

    return 0;
}
//function definition after main
int find(int x, int y){

    if(x < y){
        return y;
    }
    else{
        return x;
    }
}
Output:
Greater number is: 8

Here find() function is declared before the main function at the top but it is defined after the main function so the program will execute successfully because the compiler already knows about the find function from its declaration.

Functions in C++

A function is a set of statements that takes inputs, performs some computation, and produces output. The idea of creating a function is to put the repetitive blocks of code together and give a name. They are used to perform some specific task and instead of writing that block of code again and again you can call the function to perform that task. 

Syntax:
syntax of function
C++ Example: 
//C++ Example of a function
#include<iostream>
using namespace std;

//function definition to perform addition
int fun(int x, int y){
    
    int sum = x + y;

    return sum;
}

int main(){

    int a = 10, b = 20;
    //calling the function fun perform addition
    int sum = fun(a, b);
    cout<<"Sum: "<<sum;

    return 0;
}
Output:
Sum: 30
Note: A function without input parameters can also perform computation and return some output. (alert-success)

Why functions are used?

There are two important reasons why we are using functions:

  • Reusability: Once the function is defined, it can be reused over and over again. You can simply call the function everywhere in your program to perform that specific task. 
  • Abstraction: If you are just using the function in your program then you don't have to worry about how it works inside.

There are two types of functions:
  • Standard Library Functions: These are built-in functions that are already available in C++ programming language and you can directly use them in your code without worrying about the implementation part.
  • User-defined Functions: These are defined by the user based on their requirement to perform some specific task.
Here in this post, we are going to discuss user-defined functions in detail.


Function Declaration in C++.

A function declaration (also called function prototype) means declaring the properties of a function to the compiler. This property includes the name of the function, the return type of the function, the number of parameters, and its type. 
Note: It is not necessary to put the name of the parameter in function prototype. (alert-success) 
Example:

/*function taking two integers as 
parameter and returning an integer*/
int sum(int x, int y);

/*function taking one character as
parameter and returning a char*/
char fun(char ch);

/*function taking two-pointer variable
as a parameter and no return type*/
void sum(int*, int*);

/*function taking one integer and
one integer type pointer as a parameter
and return an integer type pointer*/
int* greater(int, int*);


Function Definition in C++.

A function definition consists of a block of code that is capable of performing some specific task. Let's understand this with an example:

Example:
//C++ Function example to add numbers
#include<iostream>
using namespace std;

//function declaration
int add(int, int);

int main(){
    
    int m = 5, n = 15, sum;
    //function call
    sum = add(m, n);
    cout<<"Sum = "<<sum;

    return 0;
}
//function definition
int add(int x, int y){
    return (x + y);
}
Output:
Sum: 20

Working of above function:
  • At first, we have declared the function "add" to have two integer type parameters and the function is going to return an integer type value. There is no need to mention the name of the variable. 
  • Inside the main function, we are calling the function "add" and pass the two arguments. You should not mention the data types of the argument or the return type of the function.
  • After the main function, we have defined our "add" function and here it is important to mention both the data type and the name of the parameters.


Error: Implicit Declaration of function

It is not necessary to declare the function before using but it is preferred to declare the function before using it. If you do not declare before using it then you will get an error "implicit declaration of function" because the compiler implicitly assumes something about the function. 
Error message:
../src/main.c:48:9: error: implicit declaration of function 'add' [-Werror=implicit-function-declaration]
         add();
You can resolve this error in two ways, declare the function before using it else define the function above the main function before calling it.


DON'T MISS

Nature, Health, Fitness
© all rights reserved
made with by AlgoLesson