What is the preferred way to read values of class members from an other class? For example: If class ClassA contains variables a,b,c, and ClassB contains a method that prints the values of a,b and c, how should an instance of ClassB that declares one instance of ClassA classA_Inst as one of it's members access the values of a, b and c from classA_Inst?

Or have I missed something :) ? There must be some better ways to do that...

05-18-2010

grumpy

There is no preferred way. There are many options and, depending on what your objects are doing, trade-offs between those options.

If the only reason the access is needed is to print the values, a simple way would be for classA to provide a public function that prints them. Then the have classB's print function call classA's print function. The advantage of this is that it allows classA to be updated without touching classB in anyway way.

05-18-2010

AdnanShaheen

Well, all of the three approaches are valid. You can any one of them. But if you consider it from the design perspective. You must look into "Coupling & Cohesion". Your classes have dependency. So it is better to remove this dependency and increase the inter class dependency by putting the print() method in the same class as well.

05-18-2010

VirtualAce

Quote:

What is the preferred way to read values of class members from an other class?

Normally this is done, as has been said, via public accessors or public 'getters'.