LearnFrenzy
Sign in Take a free test

Polymorphism and Virtual Functions · Predict the Output · Question 1

Virtual vs non-virtual call through a base pointer Answer, explanation & discussion

  • Output
  • Easy
  • 0 comments
  • Answer explained
  • Moderated community
Question 1 Back to Exercise

What is the output of the following C++ program on a 64-bit system?

main.cpp
#include <iostream>

struct Base {
    virtual void a() const { std::cout << "Ba "; }
    void b() const { std::cout << "Bb "; }
    virtual ~Base() = default;
};
struct Derived : Base {
    void a() const override { std::cout << "Da "; }
    void b() const { std::cout << "Db "; }
};

int main() {
    Derived d;
    Base* p = &d;
    p->a(); p->b(); d.a(); d.b();
    std::cout << '\n';
    return 0;
}
  • A Da Bb Da Db Correct
  • B Da Db Da Db
  • C Ba Bb Da Db
  • D Da Bb Ba Bb
Correct Answer: Option A

Through the Base pointer, the virtual a() dispatches to Derived, while the non-virtual b() uses the pointer type. Called on d directly, both use Derived.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links