1

Will there be a difference between the following two ways of calling a function from an instance? Which is better?

    Motor M;
    M.moveToPosition(Speed, TargetPosition);

    Motor *M;
    M->moveToPosition(Speed, TargetPosition);

Thanks!

W01
  • 149
  • 1
  • 12

3 Answers3

4

Your second version has Undefined Behavior, because the pointer is uninitialized!

You can dynamically allocate an object of type Motor(i.e. allocate it on the heap):

Motor *M = new Motor;
M->moveToPosition(Speed, TargetPosition);
...
delete M;

Smart Pointers will help you avoid to have to remember to delete objects allocated on the heap.

As for which is better, I am afraid it depends a lot on the context. Usually in C++ you should prefer automatic objects (on the stack) to dynamic objects (on the heap) unless you have a definite reason for the contrary.

Armen Tsirunyan
  • 120,726
  • 52
  • 304
  • 418
2

The first method will call the Motor constructor; the second method won't and the pointer will be uninitialized.

In C++, stay away from pointers where possible. Use the first method here.

If you want to dynamically allocate the motor, use this:

std::unique_ptr<Motor> M(new Motor);
M->moveToPosition(...);
0

It's the same, but using pointers you'd be able to dynamically create and destroy objects (i.e. in loops), perform operations on arbitrary number of objects, take advantage of the polymorphism, and so on.

Alexander
  • 7,989
  • 1
  • 30
  • 43