+ 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!
4 ответов
+ 2
There are many use cases for pointers - for example: polymorphism, reference semantics and avoiding copying, resource aquisition, etc.
+ 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.
+ 1
can you help me?
0
I'm really confused -_- can anyone else explain this ?