ProgrammingHardHCL · Tech Mahindra pattern
What is printed?
What is printed?
struct Base {
virtual Base& self() { cout << "Base::self "; return *this; }
};
struct Derived : Base {
Derived& self() override { cout << "Derived::self "; return *this; }
};
int main() {
Derived d;
Base &r = d.self();
r.self();
}- A. Derived::self Derived::self
- B. Derived::self Base::self
- C. Base::self Derived::self
- D. Compile-time error: Derived::self's return type must exactly match Base::self's
Correct answer: A. Derived::self Derived::self
Derived& is a covariant return type (a reference variant, also permitted). d.self() dispatches to Derived::self, printing Derived::self and binding r to the same object (still dynamically a Derived). r.self() is still a virtual call dispatched on the real object type, so it again resolves to Derived::self, printing Derived::self a second time.
More OOP with C++ and Java questions
- What is printed? java enum Status { ACTIVE, INACTIVE, BANNED; boolean isUsable() { return this == ACTIVE; } } public class Main { public…
- What happens when this is compiled? java enum Operation { ADD { public int apply(int a, int b) { return a + b; } }, MULTIPLY { public int…
- What is printed? cpp struct Logger { Logger(const Logger&) = delete; Logger& operator=(const Logger&) = delete; Logger() { cout << "Ctor…
- What is printed? java class Base { Base() { System.out.print("Base "); } } abstract class Middle extends Base { Middle() {…
- What is printed? cpp class Matrix { public: Matrix operator(const Matrix &o) const { cout << "mul "; return Matrix(); } Matrix…
- What is printed? java class Base { public Base() { System.out.print("Base() "); } } class Sub extends Base { public Sub() { super()…