ProgrammingHardHCL · Tech Mahindra pattern
What is printed?
What is printed?
struct Base {
virtual int value() const { return 10; }
};
struct Derived : Base {
int value() const override { return Base::value() + 5; }
};
struct MostDerived : Derived {
int value() const override { return Derived::value() * 2; }
};
int main() {
Base *p = new MostDerived();
cout << p->value();
}- A. 10
- B. 15
- C. 30
- D. 20
Correct answer: C. 30
MostDerived::value() explicitly calls Derived::value() (a static, non-virtual-dispatch call by qualified name), which itself explicitly calls Base::value() (returning 10), adds 5 to get 15, and MostDerived then doubles that to 30. The virtual call via p->value() dispatches to MostDerived's override, which drives this whole chain, printing 30.
More OOP with C++ and Java questions
- What is printed? java interface Payable { double rate(); default double monthly(double hours) { return hours rate(); } } class Intern…
- What is printed? cpp struct Base { virtual void print() const { cout << "Base"; } friend ostream& operator<<(ostream &os, const Base &b) {…
- What is printed? java class Shape { public boolean equals(Object o) { return o instanceof Shape; } public int hashCode() { return 1; } }…
- What is printed? java class Base { static int shared = 0; int id; Base() { id = ++shared; } } class Sub extends Base { } public class Main…
- What is printed? java class Base { Base(String tag) { System.out.print("Base:" + tag + " "); } } class Sub extends Base { Sub() {…
- What is printed? cpp struct Shape { virtual double area() const = 0; bool operator<(const Shape &o) const { return area() < o.area(); } }…