Top C++ Interview Questions and Answers

author image Hirely
at 06 Jan, 2025

Question: What is an abstract class in C++?

Answer:

An abstract class in C++ is a class that cannot be instantiated directly. It is designed to be a base class for other derived classes and contains at least one pure virtual function. The primary purpose of an abstract class is to provide a common interface (set of functions) that other derived classes must implement.

Key Characteristics of an Abstract Class:

  1. Pure Virtual Functions: An abstract class contains at least one pure virtual function. A pure virtual function is declared by assigning = 0 to the function declaration. These functions have no implementation in the abstract class itself and must be implemented by the derived class.

    Example of a pure virtual function:

    virtual void display() = 0;
  2. Cannot be Instantiated: An abstract class cannot be instantiated directly. You cannot create an object of an abstract class.

    // This will give a compilation error
    AbstractClass obj;  // Error: cannot instantiate an abstract class
  3. Derived Classes Must Implement Pure Virtual Functions: Any class that derives from an abstract class must provide implementations for all pure virtual functions, or it will also become an abstract class.

  4. Constructors and Destructors: An abstract class can have constructors and destructors. If a constructor is defined, it can be used by derived classes, but the abstract class itself cannot be instantiated.

  5. Polymorphism: Abstract classes are often used to implement polymorphism in C++, where different derived classes implement the same interface defined in the abstract class, and you can work with objects of derived classes through base class pointers or references.

Example of Abstract Class:

#include <iostream>
using namespace std;

// Abstract class
class Shape {
public:
    // Pure virtual function
    virtual void draw() = 0;  // This makes Shape an abstract class
};

// Derived class that implements the pure virtual function
class Circle : public Shape {
public:
    void draw() override {
        cout << "Drawing a circle" << endl;
    }
};

// Derived class that implements the pure virtual function
class Rectangle : public Shape {
public:
    void draw() override {
        cout << "Drawing a rectangle" << endl;
    }
};

int main() {
    // Shape obj;  // Error: cannot instantiate an abstract class

    Shape* shape1 = new Circle();
    shape1->draw();  // Output: Drawing a circle

    Shape* shape2 = new Rectangle();
    shape2->draw();  // Output: Drawing a rectangle

    delete shape1;
    delete shape2;

    return 0;
}

Output:

Drawing a circle
Drawing a rectangle

Key Points in the Example:

  • Shape is an abstract class with a pure virtual function draw().
  • The derived classes Circle and Rectangle provide implementations for the draw() function.
  • You cannot create an instance of Shape directly (e.g., Shape obj; would give a compilation error), but you can create objects of derived classes like Circle and Rectangle.
  • You can use base class pointers or references to access the derived class objects (this is an example of polymorphism).

Summary:

  • An abstract class in C++ is a class that contains at least one pure virtual function, making it impossible to instantiate directly.
  • It serves as a base class for derived classes to implement specific behavior, enforcing a common interface across different derived classes.
  • Abstract classes are widely used in object-oriented programming to define common interfaces and promote polymorphism.

Question: What is a virtual function in C++?

Answer:

A virtual function in C++ is a member function in a base class that you expect to be overridden in derived classes. When a function is declared as virtual in a base class, it ensures that the correct version of the function is called for an object, even when it is accessed through a pointer or reference to the base class. This feature is a key aspect of polymorphism in C++, allowing for dynamic binding (runtime function resolution).

Key Points About Virtual Functions:

  1. Dynamic Dispatch (Late Binding): When a function is declared as virtual, the function call is resolved at runtime rather than compile time. This is known as late binding or dynamic dispatch. The version of the function that gets called is determined by the actual object type, not the pointer or reference type.

  2. Virtual Function Declaration: A function is declared virtual in the base class by using the virtual keyword. The derived classes can override this function, providing their own implementation.

    Example:

    class Base {
    public:
        virtual void display() {  // Virtual function in the base class
            cout << "Base class display function." << endl;
        }
    };
  3. Function Overriding: In the derived class, you can override the virtual function to provide specific behavior for the derived class. The override keyword (optional but recommended) can be used to make sure that you’re actually overriding a base class virtual function.

    Example:

    class Derived : public Base {
    public:
        void display() override {  // Override the virtual function in the derived class
            cout << "Derived class display function." << endl;
        }
    };
  4. Virtual Destructor: A virtual destructor is important when you are working with inheritance and dynamic memory. It ensures that the destructor of the derived class is called when an object is deleted through a base class pointer.

    Example:

    class Base {
    public:
        virtual ~Base() {  // Virtual destructor
            cout << "Base class destructor" << endl;
        }
    };
  5. Pure Virtual Function (Abstract Function): If you want to create an abstract class that forces derived classes to implement a function, you can use a pure virtual function by setting it equal to 0. This makes the function abstract and the class abstract, meaning objects of that class cannot be instantiated directly.

    Example:

    class Base {
    public:
        virtual void display() = 0;  // Pure virtual function
    };
  6. Virtual Table (Vtable): Under the hood, C++ compilers implement virtual functions using a mechanism called a virtual table (vtable). Each class with virtual functions has a vtable, which is an array of function pointers that points to the overridden versions of the functions for that class.

Example of Virtual Function in C++:

#include <iostream>
using namespace std;

// Base class with a virtual function
class Base {
public:
    virtual void display() {  // Virtual function
        cout << "Base class display function." << endl;
    }
};

// Derived class that overrides the virtual function
class Derived : public Base {
public:
    void display() override {  // Override the virtual function
        cout << "Derived class display function." << endl;
    }
};

int main() {
    Base* basePtr;  // Pointer to the base class
    Base baseObj;
    Derived derivedObj;

    basePtr = &baseObj;
    basePtr->display();  // Calls Base class function (due to static type Base)

    basePtr = &derivedObj;
    basePtr->display();  // Calls Derived class function (due to dynamic type Derived)

    return 0;
}

Output:

Base class display function.
Derived class display function.

Explanation:

  1. Base Class Pointer: In the example, basePtr is a pointer to the Base class.
  2. Base Class Object: When basePtr points to an object of the Base class (baseObj), the display function of the Base class is called.
  3. Derived Class Object: When basePtr points to an object of the Derived class (derivedObj), the overridden display function in the Derived class is called, even though basePtr is of type Base*. This is due to dynamic dispatch (virtual function call).
  4. Polymorphism: This example demonstrates polymorphism, where the same function call (display()) results in different behavior depending on the type of object (Base or Derived), even though the pointer is of type Base*.

Summary:

  • A virtual function in C++ is a member function in a base class that can be overridden by derived classes.
  • Virtual functions support polymorphism, allowing the appropriate function to be called based on the actual object type, not the pointer type.
  • This is implemented using dynamic dispatch or late binding, ensuring that the correct function is invoked at runtime.
  • Virtual destructors are essential to ensure that the derived class destructor is called when deleting a derived object through a base class pointer.

Read More

If you can’t get enough from this article, Aihirely has plenty more related information, such as C++ interview questions, C++ interview experiences, and details about various C++ job positions. Click here to check it out.

Related Posts

Trace Job opportunities

Hirely, your exclusive interview companion, empowers your competence and facilitates your interviews.

Get Started Now