Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Object without new

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); 
like image 696
Henry B Avatar asked Nov 19 '09 16:11

Henry B


People also ask

How do you initialize a class without new?

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; } };

Can object be created without class?

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.

How do you instantiate an object in CPP?

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.


2 Answers

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); 
like image 172
Khaled Alshaya Avatar answered Oct 19 '22 09:10

Khaled Alshaya


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.

like image 44
Timo Geusch Avatar answered Oct 19 '22 08:10

Timo Geusch