afgphoenix
afgphoenix

Reputation: 79

do objects have different function members or share them?

Rectangle rect, rectb;
rect.set_values (3,4);
rectb.set_values (5,6);
rect.area();
rectb.area();

Notice that the call to rect.area() does not give the same result as the call to rectb.area(). This is because each object of class Rectangle has its own variables width and height, as they -in some way- have also their own function members set_value and area that operate on the object's own member variables.

What does it mean by -in some way- ?? does it means that functions members are shared between the objects of the class?

Upvotes: 3

Views: 141

Answers (2)

Pradyumn
Pradyumn

Reputation: 430

Yes, code of the functions for a class is loaded only once in memory, regardless of the number of objects of that class. So, in that way, it function members are shared between the objects of the class. (Perhaps the statement in that book / site could have been worded better).

So whether you call rect.set_values (3, 4) or rectb.set_values (5, 6), it is the same code that runs in memory, albeit the results may be different as the values they work with are different (the parameters received and / or data member values).

Upvotes: 1

Andreas Fester
Andreas Fester

Reputation: 36630

What does it mean by -in some way- ?? does it means that functions members are shared between the objects of the class?

Yes.

With "In Some Way", the author probably intends to describe that the code is shared, while the data (member variables) is not. Member variables are unique for each object, and the methods get a pointer to the object's data as their first parameter (which is not part of the parameter list of each method, but implicitly accessible within the method through the this pointer). Through this pointer, the same (shared) code can work on different data (different instances of the same class).

Other languages (such as Python where the parameter is called self) require to explicitly define the parameter for each member function.

Upvotes: 1

Related Questions