Site icon DataFlair

Learn Virtual Function in C++ with Real-time Example

Free C++ course with real-time projects Start Now!!

It is time to dive deep into the core concepts of C++, which makes it distinguishable from other programming languages. After completing this tutorial, you would develop a precise knowledge of the virtual function C++ that allows you to perform operations with classes and objects that you never knew existed.

Before we begin, it is important to note that a thorough knowledge of Classes and Objects in C++ is required to understand this tutorial.

We are going to discuss the following topics here to get it a better way-

What is Virtual Function in C++?

Continuing our discussion from where we left off in Polymorphism in C++. Now, it’s time to further elaborate on our discussion on Virtual functions in C++. It is important to remember that virtual function plays a vital role in achieving runtime polymorphism.

A virtual function is nothing but a member function of a base class that you redefine in a derived class. The property of redefining a member function declared in the base class to a derived class is also called Function Overriding.

If you want to call a virtual function in C++ and execute the redefined version of the member function, you can achieve this task using a pointer (*pointer_name) or a reference (->) by referring a derived class object to the base class.

A base class pointer has the capability to point to the objects of the base class and the derived class.

We can declare a member function of the base class as a virtual function with the help of the “virtual” keyword.

Rules for Virtual Function in C++

Technology is evolving rapidly!
Stay updated with DataFlair on WhatsApp!!

Here are some of the points you need to keep in mind while working with virtual functions in C++:

  1. Since we already specify the member function to be a virtual function in the base class with the help of the “virtual” keyword. Now we need not again specify it while defining it in the derived class.
  2. A member function of the base class cannot be a virtual function and a friend function simultaneously.
  3. A member function of the base class cannot be a virtual function with the keyword static.
  4. We can access virtual functions only with the help of a pointer or a reference.
  5. The basic model of the virtual function in the base class should be similar while redefining it in the derived class.
  6. It is not necessary to redefine the virtual function in the derived class. If the virtual function is not overridden, then we can use the original function declared or defined in the base class.
  7. It is not possible to introduce a virtual constructor inside the class, although it is possible to introduce a virtual destructor.

Virtual Function in C++ Significance

Now, the question arises: What is the significance of virtual functions?

So you’re not allowed to worry about this. In order to answer this question, you need to understand that virtual functions ensure that, the correct function is called for an object at the time of the function call. It as simple as it is looking, there’s nothing complicated.

Virtual Function in C++ with Example

Let us understand how we can implement a virtual function with the help of a C++ program:

#include <iostream> 
using namespace std;

class A 
{ 
// private by deafult
string data = "Data"; // Original data defined in the base class
public: 
virtual void display() // Virtual function defined in the base class
{ 
cout<<"The data is : "<<data<<endl; 
} 
}; 
class B: public A 
{ 
string value = "DataFlair"; // Virtual function redefined in the derived class
public: 
void display() 
{ 
cout << "The data is: "<<value<<endl; 
} 
}; 
int main() 
{

cout<<"Welcome to DataFlair tutorials!"<<endl<<endl;

A *a; 
B b; 
a = &b; 
a-> display(); // Changes reflected in the original data by function call
return 0; 
}

Code-

Output-

Here, we infer that changes made in the original function defined in the base class are reflected in the derived class with the help of virtual function.

Quiz on Virtual Function in C++

Time limit: 0

Quiz Summary

0 of 15 Questions completed

Questions:

Information

You have already completed the quiz before. Hence you can not start it again.

Quiz is loading…

You must sign in or sign up to start the quiz.

You must first complete the following:

Results

Quiz complete. Results are being recorded.

Results

0 of 15 Questions answered correctly

Your time:

Time has elapsed

You have reached 0 of 0 point(s), (0)

Earned Point(s): 0 of 0, (0)
0 Essay(s) Pending (Possible Point(s): 0)

Categories

  1. Not categorized 0%
  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
  15. 15
  1. Current
  2. Review / Skip
  3. Answered
  4. Correct
  5. Incorrect
  1. Question 1 of 15
    1. Question

    #include <iostream>

    using namespace std;

     

    class base {

    public:

        virtual void fun()

        {

            cout << “base “;

        }

    };

     

    class derived : public base {

    public:

        void fun()

        {

            cout << “derived “;

        }

    };

     

    int main()

    {

        base b;

        derived d;

        b.fun();

        d.fun();

    }

    Correct
    Incorrect
  2. Question 2 of 15
    2. Question

    #include <iostream>

    using namespace std;

     

    class base {

    public:

        virtual void fun()

        {

            cout << “in base”;

        }

    };

     

    class derived : public base {

    public:

        void fun()

        {

            cout << “in derived”;

        }

    };

     

    int main()

    {

        base* ptr;

        derived d;

        ptr = &d;

        ptr->fun();

    }

    Correct
    Incorrect
  3. Question 3 of 15
    3. Question

    #include <iostream>

    using namespace std;

     

    class base {

    public:

        virtual void fun()

        {

            cout <<“base fun “;

        }

        void diff()

        {

            cout<<“base diff “;

        }

    };

     

    class derived : public base {

    public:

        void fun()

        {

            cout << “derived fun “;

        }

        void diff()

        {

            cout<< “derived diff “;

        }

    };

     

    int main()

    {

        base * ptr;

        derived d;

        ptr =&d;

        ptr->fun();

        ptr->diff();

    }

    Correct
    Incorrect
  4. Question 4 of 15
    4. Question

    #include <iostream>

    using namespace std;

     

    class base {

    public:

        virtual void fun()

        {

            cout <<“base fun “;

        }

        void diff()

        {

            cout<<“base diff “;

        }

    };

     

    class derived : public base {

    public:

        void fun(int x)

        {

            cout << “derived fun “;

        }

        void diff()

        {

            cout<< “derived diff “;

        }

    };

     

    int main()

    {

        base * ptr;

        derived d;

        ptr =&d;

        ptr->fun();

        ptr->diff();

    }

    Correct
    Incorrect
  5. Question 5 of 15
    5. Question

    #include <iostream>

    using namespace std;

     

    class base {

    public:

        virtual void fun()

        {

            cout <<“base fun “;

        }

    };

     

    class derived : public base {

    public:

    };

     

    int main()

    {

        base * ptr;

        derived d;

        ptr =&d;

        ptr->fun();

    }

    Correct
    Incorrect
  6. Question 6 of 15
    6. Question

    #include <iostream>

    using namespace std;

    inline int Max(int x, int y)

    {

        return x>y?x:y;

    }

    int main()

    {

        cout << Max(3,4) << “\n”;

        return 0;

    }

    Correct
    Incorrect
  7. Question 7 of 15
    7. Question

    #include <iostream>

    using namespace std;

    class base1 {

    private:

        int y;

     

    public:

    base1(){y=10;}

    friend class base;

    };

     

    class base {

    private:

        int x;

     

    public:

        void set(base1& z) {

            x = 6;

            cout<<z.y;

        }

        

    };

    int main()

    {

        base1 b;

        base a;

        a.set(b);

        return 0;

    }

    Correct
    Incorrect
  8. Question 8 of 15
    8. Question

    #include <iostream>

     

    class B;

     

    class A {

    public:

        void print(B&);

    };

     

    class B {

    private:

        int b;

     

    public:

        B() { b = 0; }

        friend void A::print(B& x);

    };

     

    void A::print(B& x)

    {

        std::cout <<x.b;

    }

     

    int main()

    {

        A a;

        B x;

        a.print(x);

        return 0;

    }

    Correct
    Incorrect
  9. Question 9 of 15
    9. Question

    #include <iostream>

     

    class B;

     

    class A {

    public:

        void print(B&);

    };

     

    class B {

    private:

        int b;

     

    public:

        B() { b = 0; }

        friend void A::print(B& x);

    };

     

    void A::print(B& x)

    {

        std::cout <<x.b;

    }

     

    int main()

    {

        A a;

        B x;

        x.print(a);

        return 0;

    }

    Correct
    Incorrect
  10. Question 10 of 15
    10. Question

    class A;

     

    class B {

    private:

        int b;

     

    public:

        B() { b = 0; }

        void print(A& a);

    };

     

    class A {

        int z=10;

    public:

        friend void B::print(A&);

    };

     

    void B::print(A& a)

    {

        std::cout <<a.z;

    }

     

    int main()

    {

        A a;

        B x;

        x.print(a);

        return 0;

    }

    Correct
    Incorrect
  11. Question 11 of 15
    11. Question

    Which function is significantly used to reduce the function call overhead?

    Correct
    Incorrect
  12. Question 12 of 15
    12. Question

    Which function can access the private members of another class?

    Correct
    Incorrect
  13. Question 13 of 15
    13. Question

     

     Which of the following is not true about friend function?

    Correct
    Incorrect
  14. Question 14 of 15
    14. Question

    Which of the following is not true about virtual function?

    Correct
    Incorrect
  15. Question 15 of 15
    15. Question

    In what condition can the compiler ignore the inline function request?

    Correct
    Incorrect

Summary

Its been a great journey up till here. Although it was short, still it was informative and better to grasp the concept. We covered a very important topic in a very enjoyable way. It’s been difficult for an individual now to forget the concept. We learned each and every impact of virtual functions in C++. We also studied its rules, significance and tried to understand it with an example.

Get ready for the next article – Inline Function in C++

After reading the article if any individual still finds any problem then s/he can comment in the comment section below. We will try our best to serve you.

Exit mobile version