+ 1

Could someone explain me please, why is useful a pointer to a class' object, if I can simply use the name of the object in the class?

For example: Class example{ public: int changeNumber(int x){ y = x * (x + x); result = y; return result; }; } int main(){ example thisNumber; thisNumber.changeNumber(4); cout << result << endl; return 0; }; // It should output 32 Instead of: int main(){ example thisNumber; int *ptr = &thisNumber; ptr->changeNumber(4); cout << result << endl; return 0; }; Thank you!

30th Jan 2016, 4:33 PM
Matias Beraldo Fernandez
Matias Beraldo Fernandez - avatar
4 Antworten
+ 2
There are many use cases for pointers - for example: polymorphism, reference semantics and avoiding copying, resource aquisition, etc.
13th May 2016, 12:50 PM
James Flanders
+ 1
I think I understand what you are asking, but if my answer seems strange then I apologize for the misinterpretation of your query. Pointers to any type of data (variables, structures, objects, etc.) are useful to a programmer for more than one reason alone...in your situation I believe pointers would be most beneficial for keeping your main function simple, and instead using a dedicated method to create both your example class object and then use that newly created object to call the changeNumber method all from within a method that is called from the main function. This programming style is called modulation, and is meant to keep your code in your main function from becoming too verbose, and instead letting methods do all your data creation for your outside of int main.
13th Jun 2016, 12:13 PM
STLBlues
STLBlues - avatar
+ 1
can you help me?
21st Jun 2016, 1:22 PM
Terence John J. Morilao
Terence John J. Morilao - avatar
0
I'm really confused -_- can anyone else explain this ?
16th Jun 2016, 2:09 PM
Mazin Muhamed
Mazin Muhamed - avatar