ProgrammingVery hardProduct-company placement · C++
Which line fails to compile?
Which line fails to compile?
struct A { virtual ~A() { } };
struct B { virtual ~B() { } };
struct C : A, B { };
int main() {
A* a = new C;
B* b1 = dynamic_cast<B*>(a); // L1
B* b2 = static_cast<B*>(a); // L2
}- A. L1 only
- B. L2 only
- C. Both
- D. Neither
Correct answer: B. L2 only
A and B are unrelated types, so static_cast cannot convert between them. dynamic_cast can 'cross-cast' at run time because the actual object is a C that has both bases; b1 is non-null.
More OOP with C++ and Java questions
- What does the C++ standard say about this code? cpp const int x = 5; int p = constcast<int>(&x); p = 6;
- 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}) {…