pointer vs non-pointer

C

Carmen Sei

to delcare an object with pointer -
MyCar * mycar = new MyCar;
mycar->Create();

========================
to delcare an object without pointer -
MyCar mycar = new MyCar;
mycar.Create();

========================
for pointer we use ->
for non-pointer we use . (dot)

========================
I think for Java equivalent the -> is same as Java's . (dot)

========================
should I always you the MyCar * mycar = new MyCar; to initalize a new
Object?

since using -> is same as using (dot) in Java.

========================
when are the time to use the (dot) but not -> (non-pointer) then?
 
F

Fred Zwarts

Carmen Sei said:
to delcare an object with pointer -
MyCar * mycar = new MyCar;
mycar->Create();

Why is this? Does the constructor of MyCar fail to create mycar?
========================
to delcare an object without pointer -
MyCar mycar = new MyCar;

Did you try to compile this? It won't work.
The types are different at both sides of the =.
Left the type is MyCar (object), right the type is MyCar* (pointer to object).
Maybe you meant:

MyCar mycar;
mycar.Create();

========================
for pointer we use ->
for non-pointer we use . (dot)

========================
I think for Java equivalent the -> is same as Java's . (dot)

In Java (almost) everything is a pointer, so only one operator is needed.
In C++ there are objects and pointers to objects,
so two operators are used for two different cases.
"mycar->" is equivalent to "(*mycar).".
========================
should I always you the MyCar * mycar = new MyCar; to initalize a new
Object?

No, only for dynamically created objects. For other objects use MyCar mycar;.
since using -> is same as using (dot) in Java.

Approximately.
And Java has no equivalent for the C++ . (dot) operator.
========================
when are the time to use the (dot) but not -> (non-pointer) then?

When you have an variable that is not a pointer,
which may happen in fact more often than having a pointer.

Note further that, in contrast to Java, C++ has no automatic garbage cleaner
for dynamically created objects. Objects created with "new" need an explicit
"delete" to free their resources, otherwise a memory leak will be the result.
This is another reason to avoid the use of new, where possible.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,802
Messages
2,569,662
Members
45,432
Latest member
KetoMeltIngredients

Latest Threads

Top