• 13
• 18
• 19
• 27
• 10

# accessors both const and normal

This topic is 4809 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

Hi. My problem, as usual, comes from my lazyness. Here it goes. class A { protected: B* m_pB; public: B* GetB(void) { return m_pB; } const B* GetB(void) const { return m_pB; } }; So there are two same methods. What a waste! I was wandering how one could maybe write it once and have both usages. Macros are dirty, they are hard to debug. Althougt those are small methods... Templates maybe? Cheers. /def

##### Share on other sites
What's the point of protecting m_pB if any client can get raw access to it by calling a member function? If the class is a PoD class then make the members public (this class almost certainly shouldn't be PoD since it contains a pointer) otherwise design your class so that the class performs operations on m_pB instead of simply containing it and hiving it out to any Tom, Dick or Harry who wants to muck about with it, i.e.:
// BADclass A{	protected:		B* m_pB;	public:		B* GetB()		{			return m_pB;		}		const B* GetB() const		{			return m_pB;		}};void DoSomethingWithBPointer(B* pB){	if (pB)	{		pB->SomeFunction();	}}A a;DoSomethingWithPointer(a.GetB());// GOODclass A{	protected:		B* m_pB;	public:		void DoSomething()		{			if (m_pB)			{				m_pB->SomeFunction()			}		}};A a;a.DoSomething();

Enigma

##### Share on other sites
The thing is, the A class is somethimes passed to a function as const or not.
Then I have to promise, that I would be using it's B member as const too.

Class A cannot perform every operation on it's member, in every case.

If B has SOME(a lot of) interesting methods, I couldn't afford to rewrite them all to A.

Hope that makes sense.
I got to hurry now, so that had to be short.

Goodnight.
/def