ProgrammingHardMicrosoft/Google SDE MCQ · GATE CS
What is printed?
What is printed?
struct B {
virtual void f() { cout << "B"; }
void g() { f(); }
};
struct D : B {
void f() override { cout << "D"; }
};
int main() {
D d;
B b = d;
b.g();
d.g();
B* p = &d;
p->B::f();
}- A. DDB
- B. BDB
- C. BDD
- D. DDD
Correct answer: B. BDB
B b = d slices, so b is a real B and g() calls B::f (B). d.g() calls f() through this, which dispatches to D::f (D). A qualified call p->B::f() suppresses virtual dispatch (B).
More OOP with C++ and Java questions
- Which statement about this class is correct? cpp struct Buf { int p; Buf() : p(new int[8]) { } ~Buf() { delete[] p; } }; void use() { Buf…
- What is printed? cpp struct A { int x; A(int v) : x(v) { } }; struct B : A { int y; B(int v) : A(v 2), y(x + 1) { } }; int main() { B…
- What is printed? cpp struct B { B() { cout << "b"; } ~B() { cout << "~b"; } }; struct D : B { D() { cout << "d"; } ~D() { cout << "~d"; }…
- What is printed? cpp struct X { int v; X(int a) : v(a) { } bool operator==(const X& o) const { return v == o.v; } }; int main() { X a(1)…
- What happens? cpp class Shape { public: virtual double area() const = 0; }; class Square : public Shape { double s = 2; double area()…
- What is printed? cpp struct Counter { int n = 0; Counter& add(int k) { n += k; return this; } Counter addCopy(int k) { n += k; return…