Henry B
Henry B

Reputation: 8047

Why don't you have to use the new keyword to create objects?

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

Upvotes: 98

Views: 63043

Answers (4)

Timo Geusch
Timo Geusch

Reputation: 24351

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.

Upvotes: 71

digitalarbeiter
digitalarbeiter

Reputation: 2335

newPlayer is no dynamically allocated variable but an auto, stack-allocated variable:

CPlayer* newPlayer = new CPlayer(pos, attacker);

is different from

CPlayer newPlayer = CPlayer(pos, attacker);

newPlayer is allocated on the stack via the normal CPlayer(position, attacker) constructor invocation, though somewhat verbose than the usual

CPlayer newPlayer(pos, attacker);

It's basically the same as saying:

int i = int(3);

Upvotes: 7

Michael Kristofik
Michael Kristofik

Reputation: 35218

CPlayer newPlayer = CPlayer(position, attacker);

This line creates a new local object of type CPlayer. Despite its function-like appearance, this simply calls CPlayer's constructor. No temporaries or copying are involved. The object named newPlayer lives as long as the scope it's enclosed in. You don't use the new keyword here because C++ isn't Java.

CPlayer* newPlayer = new CPlayer(position, attacker);

This line constructs a CPlayer object on the heap and defines a pointer named newPlayer to point at it. The object lives until someone deletes it.

Upvotes: 12

Khaled Alshaya
Khaled Alshaya

Reputation: 96939

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

Upvotes: 83

Related Questions