In line 12 why did we added const ? | Sololearn: Learn to code for FREE!
Nouvelle formation ! Tous les codeurs devraient apprendre l'IA générative !
Essayez une leçon gratuite
17th Dec 2022, 2:08 PM
Lalala
Lalala - avatar
2 Réponses
+ 6
The const keyword in the declaration of the square() method indicates that the method does not modify the state of the object on which it is called. This is called a "const member function". By declaring a member function as const, you are promising the compiler that the function will not modify any of the object's data members. This allows the compiler to perform additional optimizations and can also help to prevent accidental modification of the object's state.
17th Dec 2022, 6:58 PM
Sadaam Linux
Sadaam Linux - avatar
+ 6
the square() method simply returns the square of the num data member without modifying it, so declaring it as const is appropriate. It is also worth noting that the const keyword can be used in the declaration of the main() function's myNum object to indicate that it is a "constant object". A constant object cannot be modified after it is initialized and must be initialized at the time it is defined.
17th Dec 2022, 6:58 PM
Sadaam Linux
Sadaam Linux - avatar