ProgrammingHardProduct-company placement · C++
What happens when this is compiled?
What happens when this is compiled?
struct P { int a; private: int b; };
int main() { P p{1, 2}; }- A. It compiles; a = 1 and b = 2
- B. It compiles; b is ignored
- C. It compiles with b default-initialised
- D. Compile-time error: P is not an aggregate and has no matching constructor
Correct answer: D. Compile-time error: P is not an aggregate and has no matching constructor
A class with a private non-static data member is not an aggregate, so brace initialisation must call a constructor, and P only has the implicit default one.
More OOP with C++ and Java questions
- Which line fails to compile? cpp struct A { int x = 1; }; struct B : protected A { }; struct C : B { int get() { return x; } }; int main()…
- std::sort(v.begin(), v.end(), [](int a, int b) { return a <= b; }); What is wrong with this call?
- What is printed? cpp int main() { priorityqueue<int> a; priorityqueue<int, vector<int>, greater<int>> b; for (int x : {3, 1, 4}) {…
- What happens when this is compiled? cpp struct Pt { int x, y; }; int main() { map<Pt, int> m; m[{1, 2}] = 5; }
- What is printed? cpp int main() { vector<int> a(3, 5), b{3, 5}; cout << a.size() << a[0] << b.size() << b[0]; }
- What is printed? cpp void f(int a[10]) { cout << (sizeof(a) == sizeof(int)); } int main() { int arr[10]; cout << sizeof(arr) /…