const/reference/pointer dilemma

Heya!

I'm currently facing a design dilemma and was hoping some of you could shed some light on what would be the "right" thing to do.

I have my class called Transform, it contains the member Matrix.
My dillema turns up because of these 2 different ways to use the matrix:
1.
 
pTransform->GetMatrix()->SetPos(0,1,23);

2.
1
2
3
4
5
6
7
8
void Transform::Update( const Transform* pParentTransform )
{
    if (pParentTransform )
    {
        //multiply this pParentTransform->GetMatrix() with this->GetMatrix()
        //this is not changing pParentTransform or it's matrix in any way.
    }
}


The dilemma I'm facing is how i should declare the GetMatrix function.

 
CMatrix& GetWorldMatrix() { return m_WorldMatrix; }

This would only work in the first case if i don't remove the const in front of pParentTransform in the update function but imo it would be wrong, since I won't change it in any way and should therefor be const.

 
const CMatrix& GetWorldMatrix() const { return m_WorldMatrix; }

This would only work in the second case for obvious reasons

 
CMatrix* GetWorldMatrix() const { return (Matrix*)&m_WorldMatrix; }

This would work for both cases but is it the right thing to do?

So, what do you think, should i just return it as a pointer with a const function like in the last snippet or is there a better way?
why dont you declare two GetWorldMatrix functions? one for not-constant objects, returning a reference. and one for const objects that will return a copy of the matrix.

1
2
CMatrix& GetWorldMatrix() {  return m_WorldMatrix; }
CMatrix GetWorldMatrix() const {  return m_WorldMatrix; }


i dont know if this is an "elegant" solution, but it should work
Yeah but You're not allowed to overload a function with the same parameter list(in this case they both have an empty parameter list). So declaring it like that would give you compiler errors.
i dont get any compiler errors, and running it, works just fine.

in fact, it is ok, to "overload" a function with the same parameterlist if one of them is const.
because non constant objects will use the function without const, and const objects will only see the const function.

an example is the at function of std::string.
http://cplusplus.com/reference/string/string/at/

1
2
const char& at ( size_t pos ) const;
char& at ( size_t pos );
ah alright, that makes perfect sence. No need for any stupid work around then, thanks a lot mate (:
Topic archived. No new replies allowed.