🎙 Free live masterclass · Sun, 29 Nov, 7:00 pm IST · Java Full Stack roadmap Register free →
Skills101
← Quiz: Inheritance and Virtual Functions: all 10 questions

Quiz: Inheritance and Virtual Functions · Question 2 of 10

What does this print? (code)

What does this print?

#include <iostream>
using namespace std;
struct A { virtual void hi() { cout << "A"; } virtual ~A() = default; };
struct B : A { void hi() override { cout << "B"; } };
int main() {
    A *p = new B();
    p->hi();
    delete p;
    return 0;
}
  1. A.A
  2. B.B
  3. C.AB
  4. D.Error
Answer & explanation

Correct answer: B

hi() is virtual, so the real object's (B's) version runs.

Can you get the rest right without peeking?

Take the timed Quiz: Inheritance and Virtual Functions quiz free. Pass it to earn XP and count towards your certificate.

Start the quiz →