What is the output of this C++ code?
#include <iostream> using namespace std; class Shape { public: virtual void draw() = 0; }; class Circle : public Shape { public: void draw() override { cout << "Drawing Circle" << endl; } }; int main() { Shape* shape = new Circle(); shape->draw(); delete shape; return 0; }
Remember that calling a pure virtual function through a derived class pointer calls the derived override.
The pointer is of type Shape*, but it points to a Circle object. The draw() method is overridden in Circle, so the Circle version runs, printing "Drawing Circle".
What is the output of this C++ program?
#include <iostream> using namespace std; class Base { public: Base() { print(); } virtual void print() = 0; }; class Derived : public Base { public: int x = 5; void print() override { cout << x << endl; } }; int main() { Derived d; return 0; }
Think about which class's constructor is running and what members are initialized at that time.
During Base's constructor, Derived's members are not yet initialized. The call to print() calls Derived's override, but since x is not initialized yet, accessing it leads to undefined behavior. The output is therefore undefined or may cause a runtime error.
What error does this code produce?
#include <iostream> using namespace std; class Animal { public: virtual void sound() = 0; }; class Dog : public Animal { public: void sound() { cout << "Woof" << endl; } }; int main() { Animal a; a.sound(); return 0; }
Can you create an object of an abstract class?
Animal has a pure virtual function, so it is abstract. You cannot create an object of an abstract class. The line 'Animal a;' causes a compilation error.
Which of the following code snippets correctly declares an abstract class in C++?
Remember the syntax for pure virtual functions.
Option C correctly declares a pure virtual function with '= 0;'. Option C misses 'virtual'. Option C defines a normal virtual function with a body, not pure. Option C uses '= 1;' which is invalid syntax.
Consider the following code. How many objects are created and what is the output?
#include <iostream> using namespace std; class Abstract { public: Abstract() { cout << "Abstract created\n"; } virtual void action() = 0; }; class Concrete : public Abstract { public: Concrete() { cout << "Concrete created\n"; } void action() override { cout << "Action done\n"; } }; int main() { Concrete c; Abstract& ref = c; ref.action(); return 0; }
Think about how many constructors run when creating a derived object.
Only one object of type Concrete is created. The Abstract constructor runs first, printing "Abstract created", then Concrete constructor prints "Concrete created". The reference ref refers to the same object. Calling action() prints "Action done".