Sign in to follow this  
raptorstrike

Do I need to call constructor?

Recommended Posts

Generally you don't 'call' constructors - they are called automatically on object creation.

In your code, Curr_Unit is a pointer to a Unit. If Existing_Unit is also a Unit pointer, then the value of the pointer will be copied and they will now point to the same place in memory. The actual object isn't copied.

If you actually want to create a new unit, copied from Existing_Unit, there are a couple of different ways to do it.

Unit* currUnit = new Unit;
*currUnit = existingUnit;

This assumes that existingUnit is an object, not a pointer, and has the = operator defined (or that the default = is appropriate).

Or:

Unit* currUnit = new Unit(existingUnit);

This uses a copy constructor to create currUnit from an existing unit object.

Anyway, you might do a little reading on pointers and make sure you understand them - they can be tricky. Also try looking up 'constructor' and 'copy constructor'.

Share this post


Link to post
Share on other sites
Quote:
Do I need to call constructor?


Constructors cannot be called, placement new excepted.

Quote:
Unit* Curr_Unit;
Curr_Unit = Existing_Unit; // where existing unit is a valid unit

so do i need to call the constructor on Curr_Unit in order for this to work?


Depends on whether you want the pointer to point to a new copy of Existing_Unit
Unit* Curr_Unit = new Unit(Existing_Unit);
The Unit class will need a constructor.

Or whether you want Curr_Unit to simply point to the existing unit, in which case you just need to get its address.

Unit* Curr_Unit = &Existing_Unit;

Share this post


Link to post
Share on other sites
Quote:
Original post by Fruny
Unit* Curr_Unit = &Existing_Unit;


Of course here, Existing_Unit must be an object, not a pointer...

other examples:

Unit Existing_Unit; // default constructor will be called. automatic.
Unit Copy_Unit( Existing_Unit ); // copy constructor will be called. also automatic.
Unit *Ptr_Unit = new Unit; // default constructor
Unit *PtrCpy_Unit = new Unit( Existing_Unit ); // copy constructor

Share this post


Link to post
Share on other sites
Quote:
Original post by raptorstrike
ok, i dont want a new unit or a copy i just want curr_unit to point to the same thing that existing_unit is pointing to so would i do this

Curr_Unit &(*Existing_Unit);//?

No need to dereference and take the address; if they're both pointers, just assign.
Curr_Unit = Existing_Unit;

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this