Giora Guttsait
Giora Guttsait

Reputation: 1300

C++ returning a non-const method in a const method

I came across this weird issue

I have a method that is a const, per se:

void doSomething() const { x(); } and x is a non-const method.
Compiling would result in a discards qualifiers error.

say I turn doSomething to int, and make x return some dummy int, and it turns into:

int doSomething() const { return x(); }

Is it normal that it would compile? it does compile on my compiler, which leads me to think this might be a compiler bug.

The compiler version is: gcc (Debian 4.4.5-8) 4.4.5


class GgWp
{
public:
    int doSomething const { return x(); }
    int x()
    {
        num = 5;
        return 0;
    }
private:
    int num;
}

As you can see, x modifies the variable num

Upvotes: 1

Views: 70

Answers (2)

johnbakers
johnbakers

Reputation: 24750

Consider this line:

int doSomething() const { return x(); }

If x() is a member function then it must be const or this will not compile on any major standards-compliant compiler. This has nothing to do with whether or not you actually return the value of x() or whether you return anything from doSomething(). You can't run a non-const function from a const function.

If x() is not a member function then this doesn't apply.

Upvotes: 3

sp2danny
sp2danny

Reputation: 7644

The const after the function name refers to the object (this) , so you should not be able to call x() (if x is not const) from a const method, and return types should make no difference.

If it compiles anyway, either x() is not a member, it's const, or your compiler is malfunctioning.

Upvotes: 1

Related Questions