Category: CPlusPlus Tutorial

  • C++ Polymorphism

    Polymorphism means having many forms. The word “poly” means many and “morphs” means forms, which means it is the way of performing some task in many ways. That means a single function or an operator functioning in many ways. It is one of the major concepts of Object-oriented programming.

    Take a real-life example: A woman can be a mother or daughter and a teacher in a class, that is she posses a different behaviour at different times or situations. Similarly, a class in a program has a method and the subclass have the same method but with a different task to perform related to the first method. This is called polymorphism.

    In C++, we have two types of polymorphism and they are:

    • Compile-time Polymorphism or Static (or early) Polymorphism.
    • Runtime Polymorphism or Dynamic (or late) Polymorphism.

    1. Compile time Polymorphism

    In this type of program, the flow of control is decided at compile time itself. It is achieved by function overloading and operator overloading. It is also known as static or early binding.

    Function Overloading:

    The multiple functions having the same name but with different parameters, then these functions are said to be overloaded. When we call those functions, we need to make sure to enter the proper number of arguments along with the proper data type.

    Example: C++ example of function overloading.

    // C++ program for function overloading
    
    #include <iostream>
    using namespace std;
    
    class OverloadProgram
    {
       public:
       int total(int num1, int num2)
       {
          return num1 + num2;
       }
    
       int total(int num1, int num2, float num3)
       {
          return num1 + num2 + num3;
       }
    };
    
    int main()
    {
       OverloadProgram obj;
    
       //calling first display function
       cout << "Result 1: " << obj.total(50, 40) << endl;
    
       //calling second display function
       cout << "Result 2: " << obj.total(7, 15, 5) << endl;
    
       return 0;
    }

    Output:

    Result 1: 90
    Result 2: 27

    Operator Overloading:

    To achieve Compile time Polymorphism, operator overloading is also used. Operator overloading means performing different operations with the same operator. The keyword ‘operator‘ is used to overload an operator.

    Example: Consider an operator ‘+‘, it is used to add the two numbers but it is also used with string to concatenate two strings. So the ‘+‘ operator when placed between number operands, addition operation is done but when placed between string operands, it concatenates them.

    Let us understand through an example: C++ program for operator overloading.

    // C++ program for operator overloading
    
    #include <iostream>
    using namespace std;
    
    class Message
    {
      string str;
      public:
        Message(string i)
        {
          str = i;
        }
    
      void operator+(Message);
      void display();
    };
    
    void Message::operator+(Message a)
    {
      string msg = str + a.str;
      cout << "The result: " << msg;
    
    }
    
    int main()
    {
      Message m1("Hi, Welcome ");
      Message m2("Home");
    
      m1 + m2;
    
      return 0;
    }

    Output:

    //Output:
    The result: Hi, Welcome Home

    2. Run time Polymorphism

    In run time polymorphism, the program is called at the time of execution that is at rum time. It is also known as the late binding or dynamic binding.

    This type of polymorphism is achieved by Method Overriding. We use virtual functions and pointers to achieve this.

    Function Overriding:

    Function overriding allows us to define a function at a derived class that is already present in a base class. And that base is said to be overridden.

    And the decision made to call the required function is done at the run time. Hence, the Runtime polymorphism.

    Example: C++ example of function overriding.

    // C++ program for function overriding
    
    #include <iostream>
    using namespace std;
    
    class Animal
    {
       public:
       void display()
       {
          cout << "I am Animal" << endl;
       }
    };
    
    class Dog: public Animal
    {
       public:
       void display()
       {
          cout << "I am a Dog" << endl;
       }
    };
    
    int main(void)
    {
       Animal anim = Animal();
       anim.display();	//parent class object 
    
       Dog dg = Dog();
       dg.display();	// derived class object
    
       return 0;
    }

    Output:

    I am Animal
    I am a Dog

    Differences between Compile time and Run time Polymorphism

    Compile-time polymorphismRun time polymorphism
    In this type of program, the flow of control is decided at compile time itself.The program is called at the time of execution that is at rum time
    It is achieved by function overloading and operator overloadingIt is achieved by function overriding and virtual function.
    Also called static or early binding.Also called late binding or dynamic binding.
    Here, the methods have the same name but with a different number of parameters or the type of parameters.Here, the methods have the same name, the same number of parameters, or the type of parameters.
    As it happens at compile-time, therefore provides a fast execution.As it happens at run-time, therefore provides a slow execution.

  • C++ Copy Constructor

    A copy constructor in C++ is used to create a copy of an already existed object. It is also used to Initialize one object from another of the same type.

    There are two types of copy constructor:

    • Default Copy constructor
    • User-Defined constructor

    Default Copy constructor:

    The default copy constructor is defined by the compiler when the user do not define a copy constructor.

    Syntax for Default Copy constructor:

    ClassName (const class_name &old_object_name)
    {
      ......
    }

    let us go through the program in C++.

    C++ Program of the copy constructor

    // C++ program for copy constructor
    
    #include <iostream>
    using namespace std;
    
    // class
    class  Rectangle {
    
      public:
           float length;
           float breadth;
           Rectangle(float l, float b)   // constructor
           { 
             length = l;
             breadth = b;
           }
           
           Rectangle(const Rectangle &obj) // copy constructor
           {
            length = obj.length;
            breadth = obj.breadth;
           }
           
           void displayArea()
           {
             float area = length * breadth;
             
             //display
             cout << "Area: " << area << endl;
           }
    };
    
    int main() 
    {
        Rectangle rect1(6, 4); //parameterized constructor
        Rectangle rect2(rect1); //copy constructor
        
        
        rect2.displayArea(); //calling through the copy constructor
        
        return 0;
    }

    Output:

    Area: 24

    Shallow Copy Constructor

    A shallow copy is a process where the copy of an object is created by copying all the member’s data exactly as it is. Default copy constructor produces the shallow copy constructor.

    Both the objects that are the original and copy point at the same memory. Since, both the object points to the same memory location, changes made by one will be reflected on other. Now since we only need to make a replica of the original object, shallow does not fully fill this purpose.

    Let us understand through an example in C++.

    // C++ program for the shallow constructor
    
    #include <iostream>
    using namespace std;
      
    
    class Rectangle 
    {
      private:
        int length;
        int *breadth;
      
      public:
        Rectangle() 
        {
            breadth = new int;
        }
    
        // Function for dimension set
        void setDimensions(int l, int b)
        {
           length = l;
           *breadth = b;
        }
      
        //display method
        void display()
        {
           cout << "Length: " << length << endl;
           cout << "Breadth: " << *breadth << endl;
        }
    };
      
    int main()
    {
        // Object of Rectangle
        Rectangle rect1;
        rect1.setDimensions(10, 5); //set data
      
        //copying rect1 at the time of initialization
        Rectangle rect2 = rect1;
        rect2.display();
      
        return 0;
    }

    Output:

    Length: 10
    Breadth: 5
    Shallow Copy constructor

    Since the pointer breadth of both the objects (original and copied) points to the same memory location, freeing one of the memory will free the other one too. So this is solved by the Deep Constructor.


    Deep Copy Constructor

    A deep copy constructor is used to overcome the problem caused by the Shallow constructor. In the deep constructor, it is like having a copy of a project but both the original and copied project are kept in separate files, that is the changes made in one of the files will not affect the other.

    A deep copy will allocate separate memory space for copied file. A user-defined copy constructor is used for the Deep copy constructor and assign dynamic memory as well if required.

    Let us understand through an example in C++.

    // C++ program for the Deep constructor
    
    #include <iostream>
    using namespace std;
      
    
    class Rectangle 
    {
      private:
        int length;
        int *breadth;
      
      public:
        Rectangle() 
        {
            breadth = new int;
        }
        
        Rectangle (Rectangle &rec)
        {
            length = rec.length;
            breadth = new int;
            *breadth = *(rec.breadth);
        }
        
        // Function for dimension set
        void setDimensions(int l, int b)
        {
           length = l;
           *breadth = b;
        }
      
        //display method
        void display()
        {
           cout << "Length: " << length << endl;
           cout << "Breadth: " << *breadth << endl;
        }
        
        //destructor
        ~Rectangle()
        {
           delete breadth;
        }
    };
      
    int main()
    {
        // Object of Rectangle
        Rectangle rect1;
        rect1.setDimensions(10, 5); //set data
      
        //copying rect1 at the time of initialization
        Rectangle rect2 = rect1;
        rect2.display();
      
        return 0;
    }

    Output:

    Length: 10
    Breadth: 5
    Deep copy constructor

    As you can see in the program above, we use destructor to destroy the dynamically allocated memory.


  • C++ Destructor

    As the name indicates, a C++ destructor destroys the object of a class as soon as the scope of an object ends. It is opposite to a constructor. When an object goes out of the scope, the compiler automatically calls the destructor function.

    Also, the destructor has the exact same name as the class, the difference is, it is prefixed with a tilde sign (~). And the destructor cannot have parameters nor modifiers.

    The syntax for C++ destructor:

    class Square
    {
        public:
         // destructor
         ~Square() 
         {
           // statement
         }   
    };

    let us see an example of a destructor in C++.


    C++ example for the Constructor and Destructor call

    // C++ program for destructor and constructor
    
    #include <iostream>
    using namespace std;
    
    // class
    class  Square 
    {
       public:
        // constructor
        Square() {
            cout << "Constructor Invoked." << endl;
        }
        //Destructor
        ~Square() {
            cout << "Destructor Invoked." << endl;
        }
    };
    
    int main() {
    
        // creating an objects of Square class
        Square sq1;
        Square sq2;
    
        return 0;
    }

    Output:

    Constructor Invoked.
    Constructor Invoked.
    Destructor Invoked.
    Destructor Invoked.


  • C++ Constructor

    In C++, a constructor is a special type of method that is called automatically when an instance of the class (object) is created. The compiler calls the constructor and is used to initialize the data members of a newly created object.

    The constructor has the same name as its class. Also, it doe not have any return type not even void.

    Let us first look at the syntax of constructor in c++

    class A
    {
      public:
         int x;
    
         // constructor
         A()
         {
           // object initialization
         }
    };

    Types of Constructor in C++

    1. Default constructor
    2. Parameterized constructor

    C++ Default constructor

    The constructor with no arguments is called a default constructor.

    Let us look into the example of the C++ default Constructor.

    // C++ program for default constructor
    
    #include <iostream>
    using namespace std;
    
    // class
    class Square
    {
       private:
          float side;
    
       public:
         // constructor
         Square()
         {
           side = 12.4;
    
           cout << "Side: " << side << endl;
         }
    };
    
    int main()
    {
       // creating an objects of Square class
       Square sq1;
    
       return 0;
    }

    Output:

    Side: 12.4

    Note: Default Constructor is used if the user does not define a constructor then the compiler creates a default constructor and initializes the member variables to its default values.


    C++ Parameterized Constructor

    A Constructor having a specific number of parameters is called Parameterized Constructor. Passing parameters is useful when you want to assign an initial value to an object at the time of its creation.

    Let us look into the example of the C++ Parameterized Constructor.

    // C++ program for Parameterized constructor
    
    #include <iostream>
    using namespace std;
    
    // class
    class Rectangle
    {
       public:
           float length;
           float breadth;
           Rectangle(float l, float b)	// constructor
           {
              length = l;
              breadth = b;
           }
           void CalArea()
           {
              float area = length * breadth;
        
             	//display
              cout << "Area: " << area << endl;
           }
    };
    
    int main()
    {
       // creating an objects of Rectangle class
       Rectangle rect1(6, 4);
       Rectangle rect2(3.5, 2.8);
    
       rect1.CalArea();
       rect2.CalArea();
    
       return 0;
    }

    Output:

    Area: 24
    Area: 9.8


  • C++ Classes and Objects

    C++ is an Object-Oriented Programming Language and classes and objects are the fundamental components of OOP’s. Everything in C++ is linked with classes and objects. The main purpose of C++ is to introduce the OOPs concept in the C programming language which itself is a powerful language.

    Objects are real-life entity and classes are the blueprint for creating an object. For example: consider a class for a car, it has color, some weight, size, etc, these are its attributes and drive, gear, brake, etc are its behaviour.

    These attributes and behaviour in a program are variables and functions in a class, also called the class members.

    C++ Class

    A class is a user-defined blueprint or prototype for creating Objects. It is a logical entity. We can say that classes are categories, and objects are items within each of those categories.

    It contains fields, methods, constructors, etc. These members of a class can be accessed and used by creating an instance of that class.

    Defining Class:

    The definition of the class starts with the keyword class followed by a class name. The body of the class is enclosed within the curly braces and ends with a semicolon. All the members of the class are declared within the body of the class as shown below.

    Syntax for class:

    class Rectangle
    {
       public:            //access specifiers
          float length;   // Length of a rectangle
          float breadth;  // Breadth of a rectangle
    
    };

    Explanation:
    The class keyword is used to create a class followed by a class name ‘Rectangle‘. the public is one of the access specifiers that are used with the class members to determine their scope that is their visibility outside of the class. There are two public variables length and breadth (attributes). And at the end of braces, a semicolon is provided to end the class.


    C++ Objects

    Objects are real-world entities that have states and behavior. Example. bike, Lamp, pen, table, etc. An object is an instance of a class. It can be physical and logical.

    All the class members are accessed by creating an object of that class. Objects are created at runtime so is called runtime entity.

    • State: It is represented by attributes of an object that is the data value.
    • Behaviour: It represents the functionality that is the behaviour of an object. Example withdraw, deposit, etc.
    //creating an object of class Rectangle
    Rectangle rect;

    Here the type is of Rectangle type rect is a reference variable that refers to the instance of a Rectangle class.

    Let us understand class and objects in C++ through an example.

    Example of C++ Class and Object

    #include <iostream>
    using namespace std;
    
    class StudentDetail   //class
    {
       public:    // Access specifier
          int stID;
          string stName;
    };
    
    int main()
    {
       // Create an instance (object) of StudentDetail
       StudentDetail stObj;
    
       // Accessing members with dot operator
       stObj.stID = 32;
       stObj.stName = "Steve Rogers";
    
       // Displaying
       cout << stObj.stID << endl;
       cout << stObj.stName;
    
       return 0;
    }

    Output:

    32
    Steve Rogers


    Example: C++ multiple objects with methods

    #include <iostream>
    using namespace std;
    
    //Car class
    class Car
    {
       public:
           string brand;
           int year;
    
       void carInfo(string br, int y)
       {
          brand = br;
          year = y;
       }
    
       void display()
       {
          cout << brand << "  " << year << endl;
       }
    };
    
    int main()
    {
       // Create two objects of Car class
       Car obj1;
       Car obj2;
    
       obj1.carInfo("BMW", 1999);
       obj1.display();
    
       obj2.carInfo("Ford", 1969);
       obj2.display();
    
       return 0;
    }

    Output:

    BMW 1999
    Ford 1969

    We created two objects (obj1, obj2) and call the methods present in the Car class with two separate objects by passing different values.


  • C++ Object Oriented Programming (OOP) Concepts

    The main purpose of C++ is to introduce the OOPs concept in C programming language which is a powerful language.

    OOP is a concept of using objects in programming. It is a paradigm that uses objects and classes that aim to implement real-world entities. The entities such as inheritance, abstraction, polymorphism, etc that are used in programming.

    There are few main principles that form the foundation of Object-Oriented programming or you can say that they are the Characteristics of an Object-Oriented Programming language. They are:

    • Class
    • Object
    • Inheritance. 
    • Encapsulation. 
    • Abstraction. 
    • Polymorphism

    Object

    Objects are real-world entities that have state and behavior. Example. bike, Lamp, pen, table, etc. An object is an instance of a class. It can be physical and logical.

    Class

    A class is a user-defined blueprint or prototype for creating Objects. It is a logical entity. We can say that classes are categories, and objects are items within each of those categories. It holds the data members and member functions and these members of a class can be accessed and used by creating an instance of that class.

    Inheritance

    Inheritance is also one of the main concepts of OOP. Inheritance is one of the processes or mechanisms in OOP in which one class(sub-class) acquires the properties(data members) and functionalities(methods) of another class(parent-class).

    This feature in C++ help to optimize the size of the code.

    Super Class: The class whose properties and functionalities are inherited by the Subclass is known as the superclass(a parent class or a base class).

    Sub Class: The class that inherits the property and behavior of the other class(Superclass) is known as a subclass( a derived class, extended class, or child class).

    Abstraction

    Data abstraction refers to the process of hiding the details but only displaying the relevant information to the world, which is hiding the implementation details and displaying only its functionalities.

    Abstraction can be achieved in two ways.

    • Abstraction class.
    • Interfaces.

    Encapsulation

    Encapsulation in C++ is defined as the wrapping up of data(variable) under a single unit. The use of Encapsulation is to make sure that implementation detail or we can say sensitive data is hidden from the users. Encapsulation is also known as data hiding

    Polymorphism

    Polymorphism means having many forms, which means it is the way of performing some task in many ways. That means a single function or an operator functioning in many ways.

    Function overloading and Function overriding are used in order to achieve Polymorphism. There is a Compile-time Polymorphism and Runtime Polymorphism.

    We will learn about each of the above concept of OOP separately in details in the further tutorial.


  • C++ Memory Management

    Memory management refers to the process of managing the computer memory while assigning the space to the program’s variable to improve the overall performance.

    Requirement of Memory Management.

    We know that data in arrays are stored in a homogeneous way. And we allocate the memory during the array declaration. But in some situations, we may not know how much memory to allocate or how much space the data may require until runtime, so to overcome this situation we declare an array with a maximum size but here the memory is unused and wasted. So to increase the array size, we can manually allocate the memory during run-time and this allocating and freeing of memory refers to dynamic memory allocation in C++ programming.

    Now, we know that in C programming, we use malloc() or calloc() functions to dynamically allocate the memory to a variable and free() function is used to free the memory. The same task is obtained in C++ with the use of new and delete Operators. Let us understand them individually.


    C++ new Operator.

    Just like malloc() or calloc(), the new operator is used to allocate the memory to a variable and arrays. The following is the way of using the new operator.

    // declare an int pointer
    int* pointerVar;
    
    //using the new keyword for dynamic allocation 
    pointerVar = new int;
    
    //value assigned to new allocate memory
    *pointerVar = 45;

    We use malloc() function in C, but it still exists in C++ but we avoid the use of malloc() in C++. The new operator has its own advantages, the main advantage is that it creates a new object in C++ which is the main concept of C++ as it involves OOP.

    It is also a Good practice to check if the free store has been used or not. You can check in the following manner.

    int* pointerVar = NULL;
    
    if(!(pointerVar = new double )) 
    {
       cout << "Error Message" <<endl;
       exit(1);
    }

    C++ delete Operator

    We use delete to free up dynamically allocated space that is to delete the dynamic memory once we no longer required it. It means deallocating the memory. The syntax for the delete operator is:

    delete pointerVar;
    
    //For arrays
    delete [] pointerVar; 

    Let us go through a simple C++ example to understand better.

    #include <iostream>
    using namespace std;
    
    int main() {
        // Initailizing pointer with Null
        int* pointerVar = NULL;
    
        // allocating memory dnamically
        pointerVar = new int;
    
        // assigning value to the memory
        *pointerVar = 458;
        
    
        cout << "Its Value: " << *pointerVar << endl;
    
        // deallocating the memory
        delete pointerVar;
    
        return 0;
    }

    Output:

    Its Value: 458

    You can also see we deallocated the memory at the end after its use.


    new and delete Operators for Arrays

    Now let us see the use of new and delete operators in arrays. Dynamic allocation increases the efficiency of memory management, especially in arrays.

    The syntax or way to allocate memory and deallocate memory is done in the following way in c++.

    //Allocating memory
    pointerVar = new data-type[size]; 
    
    //Deallocating memory
    delete [] pointerVar;  

    The syntax is for one dimensional array. You can also allocate memory to multi dimensional array in the following way:

    //Allocating memory to multi dimensional array
    pointerVar= new double [row][col];
    
    //Deallocating multi dimensional array
    delete [] pionterVar;

    As you can see deallocation is same for both one and multi dimensional arrays.

    Now let us see an C++ example for dynamic memory allocation in array.

    #include <iostream>
    using namespace std;
    
    int main() 
    {
        int number;
        float* ptr;
        
        cout << "How many students are present in your class: ";
        cin >> number;
        
        //allocating memory
        ptr = new float[number];
    
        cout << "Enter their Maths marks: " << endl;
        for (int i = 0; i < number; ++i) 
        {
            cout << "Roll " << i + 1 << ": ";
            cin >> *(ptr + i);
        }
    
        cout << "\nEntered Marks for each student." << endl;
        for (int i = 0; i < number; ++i)
            cout << "Roll " << i + 1 << ": " << *(ptr + i) << endl;
    
        // releasing the ptr memory
        delete[] ptr;
    
        return 0;
    }

    Output:

    How many students are present in your class: 5
    Enter their Maths marks: 
    Roll 1: 68
    Roll 2: 90
    Roll 3: 84
    Roll 4: 77
    Roll 5: 96
    
    Entered Marks for each student.
    Roll 1: 68
    Roll 2: 90
    Roll 3: 84
    Roll 4: 77
    Roll 5: 96

    new and delete Operators for Objects

    As said earlier, a new operator is also used to create new objects in C++. Let us understand through an example.

    #include <iostream>
    using namespace std;
    
    class Employee 
    {
       int salary;
    
       public:
    
        // constructor
        Employee() : salary(25000) {}
    
        void empSalary() 
        {
            cout << "Salary: " << salary << endl;
        }
    };
    
    int main() 
    {
        // Employee Objects Dynamically
        Employee* ptr = new Employee();
    
        //calling empSalary funciton from Employee class
        ptr->empSalary();
    
        // releasing pointer
        delete ptr;
    
        return 0;
    }

    Output:

    Salary: 25000

    In the above program, we created a Employee class where salary variable is initialized using the constructor. An in the main function, we created an object of the Employee class using a new operator and used a pointer to point to the address.

    As soon as we create the object the salary is initialized by the constructor and we use the following code to call the function empSalary() from the Employee class


  • C++ Pointer to Pointer

    As we know by now that a pointer stores the address of the pointed variable. But it is not the only use, pointer also stores the address of another pointer forming a chain like structure.

    When we defined the pointer to a pointer, it means the first pointer contains the address of the second pointer and the second pointer contains the address of an actual variable.

    Pointer to Pointer

    We can declare the pointer to pointer variable by simply adding an additional asterisk * before the pointer name. example:

    int **pointer_name;

    C++ Program for Pointer to Pointer

    #include <iostream>
    using namespace std;
     
    int main () 
    {
       int num = 100;
        
       //Pointer declaration
       int  var;
       int  *ptr1;
       int  **ptr2;
    
       //assigning address to pointer
       ptr1 = &num;
       ptr2 = &ptr1;
    
       // value present in each varibles
       cout << "Value stored by var :" << num << endl;
       cout << "Value stored byt *ptr1 :" << *ptr1 << endl;
       cout << "Value stored by **ptr2 :" << **ptr2 << endl;
    
       return 0;
    }

    Output: After execution, the following output will be displayed.

    Value stored by var :100
    Value stored byt *ptr1 :100
    Value stored by **ptr2 :100

  • C++ Passing Pointers to Functions

    A function is a user-defined block of codes that executes some specific task assigned to it invoked by its name. If there is an argument to be passed while calling a function then it is called actual arguments. There are two ways to call a function:

    • call by value
    • call by reference

    In a first way, we pass the actual values as an actual argument and those values are copied to the function and the function does some task with them. And the second way to call a function can be processed in two ways:

    • by passing the references
    • by passing the pointers

    In C++ programming, just like we pass values of the variable as parameters in the function, we can also pass addresses as an argument in functions.

    When we pass pointers in the function that means we pass the address of the variable instead of the value.

    Let us understand it through a syntax.

    // & before the parameter is used for address
    void func(int &num) 
    {
        // code
    }
    
    int main() 
    {
        int number = 10;
    
        // pass by reference
        func(number);
    
        return 0;
    }

    As you can see that the func() function takes a reference of the number variable that is the address of the number. And & is used to access the address.


    Example: Passing Pointer to Function by reference

    #include <iostream>
    using namespace std;
    
    // swap function
    void swapFunc(int *num1, int *num2) 
    {
        int temp;
        
        temp = *num1;
        *num1= *num2;
        *num2= temp;
    }
    
    int main()
    {
    
        int a = 4, b = 5;
    
        cout << "Values of a and b, before swapping" << endl;
        cout << "a: " << a << endl;
        cout << "b: " << b << endl;
    
        // calling swap function by passing a reference
        swapFunc(&a, &b);
    
        cout << "\nValues of a and b, after swapping" << endl;
        cout << "a: " << a << endl;
        cout << "b: " << b << endl;
        
        return 0;
    }
    
    

    Output: After execution of the above code, you will get the following result.

    Values of a and b, before swapping
    a: 4
    b: 5
    
    Values of a and b, after swapping
    a: 5
    b: 4

    In the above program, we use * in the swapFunc() function with passing reference to swap the number because we are dealing with the address so it is necessary to put * while using those variables.


    Return Pointer from Functions

    As we know, in C++ that array can be returned from the function, similarly, a pointer can also be returned from a function. For this, we need to declare the returning function as the pointer in the following way.

    //return int type
    int * functionName() 
    {
       //statements
    }

    Also, note that it is considered bad practice to return the address of a local variable from a function, so define the local variable as a static variable.

    Now let us see an example

    #include <iostream>
    using namespace std;
    
    //user defined funtion
    int *getArray()
    {
       static int r[5] = { 0, 10, 20, 30, 40 };
    
       for (int i = 0; i < 5; ++i)
       {
          r[i] += 5;
          cout << r[i] << endl;
       }
    
       return r;
    }
    
    //main function
    int main()
    {
       int *ptr;
    
       ptr = getArray();
    
       for (int i = 0; i < 5; i++)
       {
          cout << "*(p + " << i << ") : ";
          cout << *(ptr + i) << endl;
       }
    
       return 0;
    }

    Output:

    5
    15
    25
    35
    45
    *(p + 0) : 5
    *(p + 1) : 15
    *(p + 2) : 25
    *(p + 3) : 35
    *(p + 4) : 45

  • C++ Null Pointer

    We use a null pointer when we do not have the exact address to assign to a pointer. It is considered a good practice and null is assigned at the time of declaration. Therefore the pointer with a null value is called a null pointer.

    Check the C++ example for the null pointer.

    #include <iostream>
    
    using namespace std;
    
    int main () 
    {
       int  *ptr = NULL;
       cout << "Value of NULL pointer: " << ptr ;
     
       return 0;
    }

    Output:

    Value of NULL pointer: 0

    The value of null pointer is 0 as provided in many of the standard library.


    We can also check the pointer for null before accessing it. By doing so we can perform error handling. We can do it in a following way.

    
    if (!ptr)
    { //if will be executed if pointer is not null
        ..........
    }
    else {
    
       .......
    }