ProgrammingVery hardProduct company interview · GATE level
What is printed?
What is printed?
struct A { int v = 0; A() { cout << "A"; } };
struct B : A { B() { cout << "B"; } };
struct C : A { C() { cout << "C"; } };
struct D : B, C { D() { cout << "D"; } };
int main() {
D d;
d.B::v = 5;
cout << " " << d.C::v;
}- A. ABCD 5
- B. ABACD 0
- C. ABCD 0
- D. ABACD 5
Correct answer: B. ABACD 0
Without virtual inheritance, D contains two separate A subobjects, one inside B and one inside C, so A's constructor runs twice: A B A C D. Writing through B's copy leaves C's copy at 0. An unqualified d.v would not even compile, because it is ambiguous. Declaring B and C with virtual A would give a single shared A, print ABCD and make both paths show 5.
More OOP with C++ and Java questions
- What is printed? cpp void f(bool) { cout << "bool "; } void f(std::string) { cout << "string "; } void g(int) { cout << "int "; } void…
- What is printed on a typical platform (16-bit short, 32-bit int)? cpp int i = -1; unsigned int u = 1; short s = -1; unsigned short us = 1…
- Which lines fail to compile? cpp struct A { explicit A(int) { } }; struct B { B(int) { } }; void takeA(A) { } void takeB(B) { } int main()…
- What is printed? cpp struct N { int v = 0; N& operator++() { cout << "pre "; ++v; return this; } N operator++(int) { cout << "post "; N t…
- What is printed? java String s = "a,b,,c,,"; System.out.print(s.split(",").length);
- What is printed? java System.out.print(",x,".split(",").length + " " + "".split(",").length);