asinduvg
asinduvg

Reputation: 67

Can't we have just variables to Objects in c++?

When we are coding with java we can have reference variables that are not assigned to any object. Example : Player p1 here p1 is assigned only if we create an object like below : p1 = new Player(); Here p1 stores the address of the newly created Player object.

If we create a variable in c++ like this, it is also creating a new object. Example : Player p2 p2 here assigned to a new object. That way we cannot have any variable only of some type.

Also we can create pointers to the object as following, Player* p3 = new Player(); If both(p2 & p3) are holding addresses,

i) What use of pointer(p3) of that type?

ii) How can we just create variables to a type ?

Upvotes: 0

Views: 115

Answers (2)

besc
besc

Reputation: 2647

The closest you can get to mimic what Java does is (but see below about shared_ptr):

std::shared_ptr<Player> p;
assert(not p);  // Assertion holds!
p = std::make_shared<Player>();
assert(p);  // Assertion holds!

That’s roughly equivalent to:

Player* p = nullptr;
p = new Player;
// ...
delete p;

But that’s manual memory management, which is highly error prone. Don’t do it!

If you don’t have a pointer to an object, but just the object itself (a value in C++ terminology), you lose the empty state.

Player p;

p is the object itself. That line creates the object and there’s no way around it. There’s no indirection which before gave you the opportunity to represent “no object present”. You can add an empty state back, if you need it:

std::optional<Player> p;  // since C++17, before use boost::optional
assert(not p); // holds
p = Player();
assert(p); // holds

A note about shared_ptr. Real shared ownership is actually pretty rare. Usually you have (and want to have) exactly one owner of an allocated object. So, in most cases you want unique_ptr (if you want a pointer at all):

std::unique_ptr<Player> p;
assert(not p);  // holds
p = std::make_unique<Player>();
assert(p); // holds

Upvotes: 0

Thomas Padron-McCarthy
Thomas Padron-McCarthy

Reputation: 27632

p2 doesn’t hold an address. It contains the actual object, in the variable itself.

Upvotes: 2

Related Questions