this is a really simple question but I havn't done c++ properly for years and so I'm a little baffled by this. Also, it's not the easiest thing (for me at least) to look up on the internet, not for trying.
Why doesn't this use the new
keyword and how does it work?
Basically, what's going on here?
CPlayer newPlayer = CPlayer(position, attacker);
Bookmark this question. Show activity on this post. class Rectangle{ private: double width; double height; public: void Set(double w , double l){ width = w; height = l; } };
We can create an object without creating a class in PHP, typecasting a type into an object using the object data type. We can typecast an array into a stdClass object. The object keyword is wrapped around with parenthesis right before the array typecasts the array into the object.
Instantiating a ClassThe new operator requires a single, postfix argument: a call to a constructor. The name of the constructor provides the name of the class to instantiate. The constructor initializes the new object. The new operator returns a reference to the object it created.
This expression:
CPlayer(position, attacker)
creates a temporary object of type CPlayer
using the above constructor, then:
CPlayer newPlayer =...;
The mentioned temporary object gets copied using the copy constructor to newPlayer
. A better way is to write the following to avoid temporaries:
CPlayer newPlayer(position, attacker);
The above constructs a CPlayer object on the stack, hence it doesn't need new
. You only need to use new
if you are trying to allocate a CPlayer object on the heap. If you're using heap allocation, the code would look like this:
CPlayer *newPlayer = new CPlayer(position, attacker);
Notice that in this case we're using a pointer to a CPlayer object that will need to be cleaned up by a matching call to delete
. An object allocated on the stack will be destroyed automatically when it goes out of scope.
Actually it would have been easier and more obvious to write:
CPlayer newPlayer(position, attacker);
A lot of compilers will optimise the version you posted to the above anyway and it's clearer to read.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With