ProgrammingHardProduct-company placement · C++
What does the C++ standard say about this code?
What does the C++ standard say about this code?
const int x = 5; int* p = const_cast<int*>(&x); *p = 6;
- A. x becomes 6
- B. Compile-time error at the const_cast
- C. It throws std::bad_cast
- D. Undefined behaviour, because x was originally defined const
Correct answer: D. Undefined behaviour, because x was originally defined const
const_cast only removes const from the pointer type; writing through it is allowed only if the object itself was not defined const. Here it was, so the write is undefined (x may even be folded into a constant).
More OOP with C++ and Java questions
- For the call f(g(), h()) in C++17, which statement is correct?
- What happens when this is compiled? cpp struct P { int a; private: int b; }; int main() { P p{1, 2}; }
- 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; }