Sometimes I need to expose some of the class members. For example in the following example class Mechanic
may need direct access to Engine
componen
They can be useful when the value you are returning is actually on the heap.
template<class T> class Singleton
{
private:
static T* m_pSingleton;
public:
T& getSingleton() { assert(m_pSingleton); return(*m_pSingleton); };
}; // eo class Singleton
In this case you would rather need a Car.fix(const Mechanic&)
function which then gives the engine to the Mechanic
, say: Engine.fix(const Mechanic&)
, as I suppose the state of the Engine
will be modified.
The original idea of using classes was to tie together the data with its accessor functions. If you do setter or getter which merely returns an internal data, it means that your data is not tied together with its accessor functionality: your class is not complete.
You want only to expose new data which a class emits. Say Car.get_exhaust()
and the Car
does not have the exhaust, only produces it, when you ask so. ;)
Or Fire Riefle.fire()
whereas no access for Riefle::Trigger
will be fixed by the mechanic like so: Trigger.fix_by(Mechanic)
and then the fix_by
will call say Mechanic.add_working_hour(0.5)
. XD
Instead of thinking about exposing private members of a class think more along the lines of calling methods on those classes. I read an interesting Java article, Why Getter and Setter Methods are Evil, which applies just as much to C++ as it does to Java.