ProgrammingVery hardMicrosoft/Google SDE MCQ · GATE CS
What is printed?
What is printed?
struct B {
B() { cout << "b"; }
~B() { cout << "~b"; }
};
struct D : B {
D() { cout << "d"; }
~D() { cout << "~d"; }
};
int main() {
B* p = new D[2];
delete[] static_cast<D*>(p);
}- A. bdbd~d~b~d~b
- B. bdbd~b~b
- C. bbdd~d~d~b~b
- D. bdbd~d~b
Correct answer: A. bdbd~d~b~d~b
Each array element is built base first: b d, b d. Deleting through the correct type D* destroys the elements in reverse order, each running ~D then ~B. Deleting the array through a B* would be undefined.
More OOP with C++ and Java questions
- 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&) {…
- What is printed? cpp struct P { int x; explicit P(int v) : x(v) { } explicit operator bool() const { return x != 0; } }; int main() { P…