ProgrammingHardTCS NQT · Infosys pattern
What is printed?
What is printed?
struct Base {
virtual std::string name() const { return "Base"; }
};
struct Derived : Base {
std::string name() const override { return "Derived"; }
};
void describe(const Base& b) {
cout << "This is a " << b.name();
}
int main() {
Base b1;
Derived d1;
describe(b1);
cout << " | ";
describe(d1);
}- A. This is a Base | This is a Derived
- B. This is a Base | This is a Base
- C. This is a Derived | This is a Derived
- D. Compilation error: describe cannot bind a Derived to a const Base&
Correct answer: A. This is a Base | This is a Derived
Passing by const reference never slices; describe() receives a genuine reference to whichever object was passed. b.name() dispatches virtually based on the actual bound object each time: Base's own name() for b1, Derived's override for d1.
More OOP with C++ and Java questions
- What is printed? java class Resource { String name; Resource(String n) { name = n; } @Override protected void finalize() {…
- What is printed? cpp class Logger { public: static int instances; Logger() { instances++; } ~Logger() { instances--; } }; int…
- What is printed? cpp struct Event { virtual void handle() const { cout << "generic-event "; } }; struct ClickEvent : Event { void handle()…
- A lambda expression captures a local variable from its enclosing method. What restriction does Java place on that variable?
- In Java, instance method calls (non-static, non-private, non-final) use dynamic dispatch based on the object's actual run-time class…
- What is printed? cpp struct Vec2 { int x, y; Vec2 operator+(const Vec2& o) const { return {x + o.x, y + o.y}; } }; int main() { Vec2 a{1…