Sign in to follow this  

accessors both const and normal

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

If you intended to correct an error in the post then please contact us.

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 this post


Link to post
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.:
// BAD
class 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());

// GOOD

class A
{
protected:
B* m_pB;
public:
void DoSomething()
{
if (m_pB)
{
m_pB->SomeFunction()
}
}
};

A a;
a.DoSomething();


Enigma

Share this post


Link to post
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

Share this post


Link to post
Share on other sites

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

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this