Mobile wallpaper 1Mobile wallpaper 2Mobile wallpaper 3Mobile wallpaper 4Mobile wallpaper 5Mobile wallpaper 6
132 字
1 分钟
Consolidation6 Program's Output

What will be the output of the following C++ program?#

#include <iostream>
using namespace std;
class A{
public:
A(){ cout<<"Constructor called\n"; }
~A(){ cout<<"Destructor called\n"; }
};
int main(int argc, char const *argv[]) {
A *a = new A[4];
delete[] a;
return 0;
}

Code behavior#

A *a = new A[4];
  • This dynamically allocates an array of 4 objects of class A.
  • The constructor is called once for each object, in order.
delete[] a;
  • This deletes the array.
  • The destructor is called once for each object, in reverse order.

Order of calls#

  1. Constructors (called 4 times):

    • Object 1
    • Object 2
    • Object 3
    • Object 4
  2. Destructors (called 4 times, reverse order):

    • Object 4
    • Object 3
    • Object 2
    • Object 1

Output#

Terminal window
Constructor called
Constructor called
Constructor called
Constructor called
Destructor called
Destructor called
Destructor called
Destructor called

Key Concept (Exam Tip)#

  • new[] → constructor called for each element
  • delete[] → destructor called for each element in reverse order
Consolidation6 Program's Output
https://mizuki.anka2.top/posts/l5-cpp-week12-lecture/consolidation6-program/
作者
🐦‍🔥不死鸟Anka
发布于
2025-12-15
许可协议
MIT

部分信息可能已经过时

封面
Sample Song
Sample Artist
封面
Sample Song
Sample Artist
0:00 / 0:00