#include<iostream>
using namespace std;
class test
{
public:
test(){cout<<"Constructor called ";}
};
int main()
{
test a,*b;
return 0;
}
I expected the constructor to be called two times. Why does a pointer object did not call the default constructor
A pointer is just a pointer. It can point to an object but it does not necessarily do so. Declaring a pointer does not automagically create an instance. Your pointer is not initialized to point anywhere.
For a far-fetched analogy consider I give you a paper on which it is written: "My wallet". I didn't give you any money, I just gave you a "pointer" to where you can find money (not necessarily, only if there actually is money in my wallet). For your code the better analogy is: I give you an empty piece of paper. In any case, giving you a "pointer" to where you can find money, unfortunately does not create money in my wallet:(
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.