OA. free
Free
MathWorks Core Computer Science Core Computer Science Medium

What will be the output of following code?

MathWorks technical mcq question, verified with a worked answer. Free to practise - no sign-up.

What will be the output of following code?**

#include<iostream>
using namespace std;

class Base
{
    public:
        virtual void show() = 0;
        virtual void print() = 0;
};

class Derived:public Base
{
    public:
        void show()
        {
            cout <<"Show Function in Derived class called";
        }
};

int main()
{
    Base obj;
    Base *b;
    Derived d;
    b = &d;
    b->show();
}

Pick ONE OR MORE options

Choose one option.
Show answer & explanation
Answer: B. Compile time error

The code fails at compile time because Base is an abstract class with two pure virtual functions (show() and print()). The Derived class only implements show() but not print(), making Derived also abstract. Therefore, instantiating Derived d in main() violates the constraint that abstract classes cannot be instantiated. The compiler rejects this before execution.

Step-by-step Derivation:

  1. Base class has two pure virtual functions: show() = 0 and print() = 0, making Base abstract.
  2. Derived class inherits from Base and implements only show(), leaving print() as pure virtual.
  3. Since Derived does not implement all pure virtual functions, Derived remains abstract.
  4. Line 'Derived d;' in main() attempts to instantiate an abstract class, which is illegal in C++.
  5. The compiler generates a compile-time error: 'cannot declare variable of abstract type Derived' (or similar).
  6. The code never reaches runtime; no output is produced.