Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Does this typecast the return value to a const? bool foo() const { return bar; }?

Here’s the snippet in title (more readable) bool foo() const { return bar; }?

If not, is it different from const foo() {return bar;}? Or is it the same thing as saying the argument the function takes is a constant?

I’ve tried scouring cppreference and can’t find anything.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The const in the first code snippet:

bool foo() const { return bar; }

Means that the method does not modify the instance of the class that owns the method. Let’s add some more code to make this clear:

bool bar = true;

struct Foo {
    bool foo() const { return bar; }
};

int main() {
    const Foo f;
    f.foo();
    return 0;
}

When f.foo() is called the instance f is not modified. That is the meaning of the const in your snippet. It has nothing to do with the return value bar

The second code snippet is a compiler error. It would return a const foo if it had an identifier

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading