Allegro.cc - Online Community

Allegro.cc Forums » Programming Questions » operator overloading question

Credits go to Karadoc ~~, Stas B., and Tobias Dammers for helping out!
This thread is locked; no one can reply to it. rss feed Print
 1   2 
operator overloading question
bamccaig
Member #7,536
July 2006
avatar

Returning a reference to a const should be a contract between the caller and object that the referenced object will persist for at least as long as the returning object itself and that the caller is not to modify it. So long as this contract is upheld then there's no harm. Even better if the returned object is immutable.

I would agree that an object that exposes a keyboard state should support an interface to check the state of a key rather than returning the internal state. You might offer a way to query multiple keys at a time, but I would prefer that interface to return a copy of internal state.

void Keyboard::getKeyStates(std::map<int,bool> & in_out) const
{
    for(std::map<int,bool>::iterator it = in_out.begin();
            it != in_out.end();
            it++)
    {
        int key = it->first;

        results[key] = this->getKeyState(key);
    }
}

Stas B.
Member #9,615
March 2008

Also note that this solution does not violate encapsulation at all - the KeyStates class adheres to the "do one thing" philosophy, and allows for a very narrow interface, providing nothing but read-only access to a snapshot of key states. By contrast, if you pass an instance class Keyboard into a function, that function can do EVERYTHING the Keyboard class exposes - read key states, change modifier states, set LED status, change keyboard layout, etc.; OTOH, if you only pass an immutable KeyStates object, the function can do nothing but read key states.

That's actually a pretty sound solution. I guess I misunderstood your post.

Tobias Dammers
Member #2,604
August 2002
avatar

Stas B. said:

That's actually a pretty sound solution. I guess I misunderstood your post.

No harm done ;)

---
Me make music: Triofobie
---
"We need Tobias and his awesome trombone, too." - Johan Halmén

 1   2 


Go to: