Search code examples
c++new-operator

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

Solution

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