What is the difference in doing:
vs.Code:MyClass x; x.function();
and what is the reason for using one method over the other?Code:MyClass x = new MyClass(); x->function();
Any help is appreciated.
Thanks.
What is the difference in doing:
vs.Code:MyClass x; x.function();
and what is the reason for using one method over the other?Code:MyClass x = new MyClass(); x->function();
Any help is appreciated.
Thanks.
The difference is that the first one exists and the second one doesn't. You can make the second one work by doing
The idea being is that x is not an object itself, it merely points to some other object that already exists (or in this case, is created at the time).Code:Myclass *x = new MyClass(); x->function();
Having pointers allows for polymorphism, as you can see by the other top five threads in the forum today.
Generally you should prefer the first method over the second unless you have a specific reason to use the second (like polymorphism as tabstop said).
In addition, the second example is missing an important part- the delete. You have to delete anything you allocate with new, which is a big reason why the first method is preferred in the simple case.
Finally, for occasions where you want to use the second version, it's generally a good idea to get in the habit of using smart pointers so that you don't forget to delete the memory and destroy the object you allocated and so it gets cleaned up automatically like the first version.
Thanks, ... and I meant to put *x