The Phantom Spaceship
Test your C++ programming skills by solving the given puzzle about object construction and virtual function behavior.
We'll cover the following
Puzzle code
Carefully read the code given below:
#include <iostream>#include <string>struct GameObject{GameObject() { std::cout << "Created a " << getType() << "\n"; }void render() const { std::cout << "Rendered a " << getType() << "\n"; }virtual std::string getType() const { return "GameObject"; }};class Spaceship : public GameObject{std::string getType() const override { return "Spaceship"; }};void display(const GameObject &gameObject) { gameObject.render(); }int main(){GameObject gameObject;Spaceship spaceship;display(gameObject);display(spaceship);}
Your task: Guess the output
Try to guess the output of the above code. Attempt the following test to assess your understanding.
Let’s discuss this code and output together in the next lesson.
Level up your interview prep. Join Educative to access 70+ hands-on prep courses.