简体   繁体   中英

Why does using a pointer with a class with no default constructor work here and not using no pointer

I have a class like the following...

MyClass {
  public:
    int myA;
    int myB;

    MyClass(int a, int b) {
      myA = a;
      myB = b;
    }
};

in my main.cpp file I try to use this class and it works.

MyClass myClass(3, 4);

I also try to do the following...

MyClass myClass;

but that doesn't work and says there is not default constructor. I understand that under the hood there is no default constructor being supplied because I supplied MyClass with a constructor.

I noticed that to achieve what I want I can do the following...

MyClass *myClass;

and that does work. I don't understand why this is the case and would like an explanation if anyone can please help.

MyClass *myClass;

This line does not call any constructor for your class, because it does not create an instance. It just creates a pointer, pointing to nothing in particular. If you want it to point to an instance of your class, you have to call a constructor to create one and you will have the same problem as before.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM