ProgrammingHardMicrosoft/Google SDE MCQ · GATE CS
What is printed?
What is printed?
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 b(5);
cout << b.x << " " << b.y;
}- A. 10 6
- B. 5 6
- C. 10 11
- D. 5 11
Correct answer: C. 10 11
The base A is initialised first with v * 2 = 10, so by the time y is initialised, x is already 10 and y = 11. Using x here is safe because base subobjects are constructed before members.
More OOP with C++ and Java questions
- 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…
- Which statement about virtual functions and templates in C++ is correct?
- What is printed? cpp struct B { B() { cout << "B"; } B(const B&) { cout << "c"; } }; struct D : B { D() { cout << "D"; } D(const D&) {…