Interview questions on virtual keyword in C++

nterview questions on the virtual keyword in C++.

This article is mainly focused on the most repeatedly asked and the latest updated interview questions on the virtual keyword in C++ that are appearing in most of the C++ interviews.

If you are looking for “C++ interview questions on virtual keyword” or “advanced C++ interview questions on virtual keyword, then you at the right place. Here I have tried to create some collection of “Some interview questions with answers related to the virtual keyword in C++ ” that might ask by your interviewer.

I hope these C++ interview questions with the answer will be helpful. If you have any other important questions related to the virtual keyword in C++ programming and concept, then please write in the comment box. It will be helpful for others.

 

Q #1) Can we have a virtual destructor in C++?

Yes, the destructor could be virtual in C++.

 

Q #2) When to use virtual destructors?

When we will delete an object of the derived class using a pointer to the base class that has non-virtual destructor a result in undefined behavior.

So virtual destructors are useful when you might potentially delete an instance of a derived class through a pointer to base class. Let see an example code,

#include<iostream>
using namespace std;
class base
{
public:
    base()
    {
        cout<<"Constructing base \n";
    }
    virtual ~base()
    {
        cout<<"Destructing base \n";
    }
};
class derived: public base
{
public:
    derived()
    {
        cout<<"Constructing derived \n";
    }
    ~derived()
    {
        cout<<"Destructing derived \n";
    }
};
int main(void)
{
    derived *d = new derived();
    base *b = d;
    delete b;
    return 0;
}

Output:

Constructing base
Constructing derived
Destructing derived
Destructing base

 

Q #3) Can we have a virtual constructor in C++?

The Constructor can’t be virtual as the constructor is a code that is responsible for creating an instance of a class and it can’t be delegated to any other object by virtual keyword means.

 

Q #4) What is the virtual function?

When derived class overrides the base class function by redefining the same function. If a client wants to access redefined the method from derived class through a pointer from the base class object, then you must define this function in the base class as a virtual function.

Let see an example, where derived class function called by base class pointer using virtual keyword.

#include<iostream>
using namespace std;
class base
{
public:
    virtual void print()
    {
        cout << "print base class" << endl;
    }
};
class derived: public base
{
public:
    void print()
    {
        cout << "print derived class" << endl;
    }
};
int main(void)
{
    //derive class object
    derived d;
    //Base class pointer
    base *b = &d;
    // virtual function, binded at runtime
    b->print();
    return 0;
}

Output:

print derived class

 

Q #5) Write some important rules associated with virtual function?

Below we are mentioning few rules for virtual function in C++.

  • Virtual functions cannot be static and also cannot be a friend function of another class.
  • Virtual functions should be accessed using pointer or reference of base class type to achieve run time polymorphism.
  • The prototype of virtual functions should be the same in the base as well as derived class.
  • They are always defined in the base class and overridden in the derived class. It is not mandatory for the derived class to override (or re-define the virtual function), in that case, the base class version of the function is used.
  • A class may have a virtual destructor but it cannot have a virtual constructor.

 

Q #6) How virtual functions are implemented C++?

Virtual functions are implemented using a table of function pointers, called the VTABLE. There is one entry in the table per virtual function in the class. This table stores the address of the virtual function and it is created by the constructor of the class.

The object of the class containing the virtual function contains a virtual pointer (vptr) that points to the base address of the virtual table in memory. Whenever there is a virtual function call, the v-table is used to resolve the function address.

Due to the vptr, the size of the object increases by the size of the pointer. The vptr contains the base address of the virtual table in memory. Note that virtual tables are class-specific, i.e., there is only one virtual table for a class irrespective of the number of virtual functions it contains.

At the time when a virtual function is called on an object, the vptr of that object provides the base address of the virtual table for that class in memory. This table is used to resolve the function call as it contains the addresses of all the virtual functions of that class. This is how dynamic binding is resolved during a virtual function call.

Note: You should not call the virtual function in the constructor. Because the vtable entries for the object may not have been set up by the derived class constructor yet, so you might end up calling base class implementations of those virtual functions.

 

Q #7) Can virtual functions be inlined?

Whenever a virtual function is called using a base class reference or pointer it cannot be inlined (because the call is resolved at runtime), but whenever called using the object (without reference or pointer) of that class, can be inlined because the compiler knows the exact class of the object at compile time.

 

Q #8) Can a virtual function is called inside a non-virtual function in C++?

Yes, we can.

 

Q #9) What is a pure virtual function in C++?

A pure virtual function (or abstract function) in C++ is a virtual function for which we don’t have an implementation, we only declare it. A pure virtual function is declared by assigning 0 in the declaration.  We can not instantiate the abstract class and we have to define it in the derived class.

Let see the below example,

#include<iostream>
using namespace std;
class Base
{
public:
    //pure virtual function
    virtual void fun() = 0;
};
class Child: public Base
{
public:
    void fun()
    {
        cout << "Child class fun is called";
    }
};
int main(void)
{
    Child d;
    d.fun();
    return 0;
}

Output:

Child class fun is called

 

Q #10) Difference between Virtual function and Pure virtual function in C++?

There are some differences between a virtual function and a pure virtual function that I have arranged in a table for easier comparison:

 

VIRTUAL FUNCTION PURE VIRTUAL FUNCTION
Syntax: virtual int fun(); Syntax:  virtual int fun() = 0;
A virtual function is a member function of the base class which can be redefined by the derived class. A pure virtual function is a member function of the base class whose only declaration is provided in the base class and must be defined in the derived class.
Classes having virtual functions are not abstract. The base class containing pure virtual function becomes abstract.
The definition is given in base class. No definition is given in base class.
The base class having virtual function can be instantiated i.e. its object can be made. The base class having pure virtual function becomes abstract i.e. it cannot be instantiated.
If a derived class does not redefine the virtual function of the base class, then it does not affect compilation. If a derived class does not redefine the virtual function of the base class, then compilation error occurs.
All derived class may or may not redefine the virtual function of base class. All derived classes must redefine the pure virtual function of the base class.

Note: Note that C++11 brought a new use for the delete and default keywords which looks similar to the syntax of pure virtual functions:

my_class(my_class const &) = delete;
my_class& operator=(const my_class&) = default;

 

Q #11) Why is a pure virtual function initialized by 0?

The reason =0 is used is that Bjarne Stroustrup didn’t think he could get another keyword, such as “pure” past the C++ community at the time the feature was being implemented. This is described in his book, The Design & Evolution of C++, section 13.2.3:

 

Q #12) Can virtual functions be private in C++?

Yes, the virtual function can be private. Let see an example code,

#include<iostream>
using namespace std;
class Base
{
public:
    void test();
private:
    virtual void fun()
    {
        cout << "Base Function"<<endl;
    }
};
class Derived: public Base
{
public:
    void fun()
    {
        cout << "Derived Function"<<endl;
    }
};
void Base::test()
{
    Derived objDerived;
    Base *ptr = &objDerived;
    ptr->fun();
}
int main()
{
    Base Obj;
    Obj.test();
    return 0;
}

Output:

Derived Function

 

Q #13) What is an abstract class?

An abstract class is a class for which one or more functions are declared but not defined (have one or more functions pure virtual), meaning that the compiler knows these functions are part of the class, but not what code to execute for that function. These are called abstract functions. Here is an example of an abstract class.

class shape
{
public:
    virtual void Calculate() = 0;
};

So we can not be instantiated, abstract class.

 

Q #14) Write down some important points related to abstract function?

There are some important points related to the abstract function.

  • A class is abstract if it has at least one pure virtual function.
  • We can create pointers and references to abstract class type.
  • If we do not override the pure virtual function in the derived class, then derived class also becomes an abstract class.
  • An abstract class can have constructors.

 

Q #15) What is the difference between a concrete class and an abstract class?

Abstract class:

An abstract class is a class for which one or more functions are declared but not defined (have one or more functions pure virtual), meaning that the compiler knows these functions are part of the class, but not what code to execute for that function. These are called abstract functions. Here is an example of an abstract class.

class shape
{
public:
    virtual void Calculate() = 0;
};

So we can not be instantiated, abstract class.

concrete class:

A concrete class is an ordinary class that has no pure virtual functions and hence can be instantiated.

class message
{
public:
    void Display()
    {
        cout <<"Hello";
    }
};

 

Q #16) How to access derived class function from the base class object without using virtual function?

Using the typecasting we can call derive class object but not recommended because you have a virtual keyword. Let see an example program for the same,

#include<iostream>
using namespace std;
class A
{
public:
    A() {};
    ~A() {};
    void fun()
    {
        cout << "Base Class fun"<<endl;
    }
};
class B: public A
{
public:
    B() {};
    ~B() {};
    void fun()
    {
        cout << "Child Class fun"<<endl;
    }
};
int main()
{
    B bObj;
    A *aObj = &bObj;
    aObj->fun();
    return 0;
}

Output:

Base Class fun.

 

Now access derived class member using the typecasting but is not recommended,

#include<iostream>
using namespace std;
//Base class
class A
{
public:
    A() {};
    ~A() {};
    void fun()
    {
        cout << "Base Class fun"<<endl;
    }
};
//Child class
class B: public A
{
public:
    B() {};
    ~B() {};
    void fun()
    {
        cout << "Child Class fun"<<endl;
    }
};
int main()
{
    B bObj;
    A *aObj = &bObj;
    //Now Access child class but not recommended
    static_cast<B*>(aObj)->fun();
    return 0;
}

Output:

Child Class fun.

 

Q #17) What is the Diamond problem? How can we get around it?

C++ allows multiple inheritances. Multiple inheritances allow a child class to inherit from more than one parent class. The diamond problem occurs when two superclasses of a class have a common base class. For example, in the following diagram, the “D class” gets two copies of all attributes of “A class”, this causes ambiguities. Let see the below image which shows what happens without virtual inheritance?

A   A  
|   |
B   C  
 \ /  
  D

 

The solution to this problem is the ‘virtual’ keyword. We make the classes “B” and “C” as virtual base classes to avoid two copies of class “A” in the “D” class.

  A  
 / \  
B   C  
 \ /  
  D

 

Q #18) Why virtual functions cannot be static in C++?

Virtual functions are invoked when you have a pointer/reference to an instance of a class. Static functions aren’t tied to a particular instance, they’re tied to a class.

 

Q #19)Do all virtual functions need to be implemented in derived classes?

The derived classes do not have to implement all virtual functions themselves. See the below example code,

#include<iostream>
using namespace std;

class base
{
public:
    virtual void print()
    {
        cout << "print base class" << endl;
    }

    virtual void display()
    {
        cout << "print base class" << endl;
    }


};


class derived: public base
{
public:
    void print()
    {
        cout << "print derived class" << endl;
    }
};


int main(void)
{
    //derive class object
    derived d;
    //Base class pointer
    base *b = &d;

    // virtual function, binded at runtime
    b->print();

    return 0;
}

Output:

print derived class

 

Q #20)Do all pure virtual functions need to be implemented in derived classes?

We have to implement all pure virtual functions in derived class only if the derived class is going to be instantiated. But if the derived class becomes a base class of another derived class and only exists as a base class of more derived classes, then derived class responsibility to implement all their pure virtual functions.

The “middle” class in the hierarchy is allowed to leave the implementation of some pure virtual functions, just like the base class. If the “middle” class does implement a pure virtual function, then its descendants will inherit that implementation, so they don’t have to re-implement it themselves. Let see an example code to understand the concept.

#include<iostream>
using namespace std;

class ISuperbase
{
public:
    virtual void print() = 0;
    virtual void display() = 0;
};


class Base: public ISuperbase
{
public:
    virtual void print()
    {
        cout << "print function of middle class" << endl;
    }
};


class Derived :public Base
{
    virtual void display()
    {
        cout << "In display function" << endl;
    }
};


int main(void)
{
    //derive class object
    Derived d;

    // virtual function, binded at runtime
    d.print();

    return 0;
}

Output:

print function of middle class

 

 

Recommended Articles for you:

 



Leave a Reply

Your email address will not be published. Required fields are marked *