I have started writing a really basic tile engine in C++ and I'm not entirely sure when to use const return values. Should I use them in cases like this

class A
{
    private:
        Rectangle hitBox;

    public:
        A();
        const bool Collision(const Rectangle& hitBox2);
};

or is it totally pointless?

Recommended Answers

All 2 Replies

The const return value in that example is pointless and does nothing. The time to use const return value is when the method is returning a reference or pointer to one of it's data items, assuming you don't want the calling function to change the value.

class foo()
{
public:
   const int& foo(int index)
   {
      return items[index];
    }
private:
   vector<int> items;
}

Put const after the function name is a different matter, it means the function changes nothing. For example, the following is an error.

class foo
{
public:
    foo() {}

    bool bar() const
    {
        x = 1;  // <<<<< Error because function is const
        return true;
    }
private:
    int x;
};

If you are returning by value on built in type, don't return it constant. It might confuse the user, but its arguable. See here

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.