Time t (12, 0, 0); t.GetTime();
Time* t = new Time(12, 0, 0); t->GetTime();
Is this Correct way to call a method using object that are created without new keyword and with new keyword??? Thanks..
Time t (12, 0, 0); t.GetTime();
Time* t = new Time(12, 0, 0); t->GetTime();
Is this Correct way to call a method using object that are created without new keyword and with new keyword??? Thanks..
Excerpt 1
Time t (12, 0, 0);
Since t
is a struct or class of type Time
, you access its members with the .
operator, known as element selection by reference.
t.GetTime();
Excerpt 2
Time* t = new Time(12, 0, 0);
Here, t
is a pointer to Time
and so you can first de-reference the pointer and then use the .
operator like before:
(*t).GetTime();
Or the short cut way that you used, which uses the element selection through pointer operator, ->
:
t->GetTime();
As Armin correctly points out, the form of element access that you need to use is determined by the type of the variable through which you access the element. It is not determined by the way in which the object is created. For example:
Time t1 (12, 0, 0);
Time *t2 = &t1;
t1.GetTime();
t2->GetTime();
(&t1)->GetTime();
(*t2).GetTime();
The difference between the two are that the first allocates memory on the stack and the second on the heap:
Time t (12, 0, 0); //t is an object on the stack
Time* t = new Time(12, 0, 0);//t is a pointer to an object on the heap
Note that using the second way requires a call to:
delete t;
when you finish using it.
Assuming you have Time class and GetTime function inside it, It's Correct but you should release the memory by delete t for 2nd one, because it's not deleted automatically