Ty_
Ty_

Reputation: 848

Can C++ pointers be initially created rather than creating a variable and then making a pointer for it?

In all of my classes the professors have stressed using this technique for creating an item and a pointer for it to be passed around:

Updated Just a mistake while typing. Too used to java.

Item item;
Item* pItem = &item;

Now you can safely pass around item using pItem without duplicating item in memory. However, what if I was to just do the following:

Item* item = new Item;

Then I have a pointer that I can dereference in main or what have you, and a point that I can simply pass around and as a variable and be confident that it will not be duplicated.

Is there something wrong with creating the pointer as I create a new object?

Also I am coming back to C++ after a while with Java to spend my summer with ALLEGRO5, so can someone please clearly explain the different ways to create a new object in CPP, and what each method actually does?

Does:

Item item;

actually make a new Item object, or like Java is it just an null reference?

Upvotes: 0

Views: 160

Answers (3)

Greg
Greg

Reputation: 1660

If you are looking for a way to pass an item without copying its memory (or do even heavier things in copy constructor), then you might consider references instead of raw pointers.

The references do not have all the flexibility of pointers (i.e. they cannot become NULL or point to different object after created), but they are much cleaner in terms of object ownership and lifecycle (having reference you will never own nor be responsible for freeing object; with const reference to temporary you might get ownership, but that's all).

Instead of raw pointers, you could consider smart pointers, but they introduce additional cost, unlike references.

Upvotes: 1

Alok Save
Alok Save

Reputation: 206528

Is there something wrong with creating the pointer as I create a new object?

There is nothing wrong. But you should consider the following:

  • Do you really need a dynamically allocated object to begin with?
  • How about ownership semantics, perhaps smart pointer can serve you better than raw pointer.

Item item;

Creates a new object. And the lifetime of this object depends on the scope at which it is created,
If this object is created globally, it lives throughout the lifetime of the program.
If it is created locally, it lives within the scope { } in which it was created.

Upvotes: 3

Mike DeSimone
Mike DeSimone

Reputation: 42805

Uhh, this does not work because new Item returns an Item*:

Item item = new Item;

And this is standard practice practice for a heap-allocated (i.e. released by delete) object:

Item* item = new Item;

I think your professor actually said:

Item item;
Item* pItem = &item;

Which is standard practice for a stack-allocated (i.e. released by leaving its scope) object.

Upvotes: 4

Related Questions