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!
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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):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.