开发者

Why is the constructor for my class not being called in this case?

开发者 https://www.devze.com 2023-04-07 05:08 出处:网络
I am 开发者_如何学Pythoncreating a new class instance like this: Cube* cube1; There is code in the Cube constructor, but it\'s not being run! Is this usual?You\'re actually not creating any instanc

I am 开发者_如何学Pythoncreating a new class instance like this:

Cube* cube1;

There is code in the Cube constructor, but it's not being run! Is this usual?


You're actually not creating any instance.

the variable you're calling cube1 is a pointer to a Cube.

To create a Cube you should have:

Cube* cube1 = new Cube();

This create a new instance of Cube in heap memory, you should call delete cube1 once you don't use it anymore.

or:

Cube cube1;

This create a new instance of Cube in stack memory, it will be destroyed once it goes out of scope.

PS. you should get a C++ textbook.


You're not creating an instance of a Cube; you're creating a pointer to a Cube.

To create a pointer to a new instance of a Cube, you'd want code like this:

Cube* cube1 = new Cube;

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号