ProgrammingHardIBM · Deloitte pattern
What is printed?
What is printed?
struct Base {
virtual void save() { cout << "BaseSave "; }
};
struct Derived : Base {
void save() override { cout << "DerivedSave "; Base::save(); }
};
int main() {
std::unique_ptr<Base> p = std::make_unique<Derived>();
p->save();
}- A. DerivedSave
- B. BaseSave
- C. DerivedSave BaseSave
- D. Compile-time error: cannot explicitly call Base::save() from an override
Correct answer: C. DerivedSave BaseSave
p->save() dispatches virtually to Derived::save (since the managed object is a Derived), printing DerivedSave; inside it, the explicit, statically-bound call Base::save() runs Base's own implementation too, printing BaseSave. Output: DerivedSave BaseSave.
More OOP with C++ and Java questions
- What is printed? java class Animal { String sound() { return "..."; } } class Dog extends Animal { @Override String sound() { return…
- What is printed? cpp struct Base { virtual int value() const { return 10; } }; struct Derived : Base { int value() const override { return…
- 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…