Problem with constexpr keyword with classes

Viewed 51

So I recently saw this snippet on the internet:

class Human
{
    int age;

public:
    constexpr Human(int humansAge) : age(humansAge) {}
    constexpr int GetAge() const { return age; }
};

int main(int argc, char const *argv[])
{
    constexpr Human somePerson(15);
    const int hisAge = somePerson.GetAge();

    return 0;
}

Now I've compared this class with and without the keyword constexpr on compiler explorer and I saw that the constructor didn't have it's instructions on the right side, but the function GetAge had them, Now I have some questions:

  1. What is constexpr doing here to the constructor and the function GetAge?
  2. What is the role of the const keyword after the prototype of GetAge(), does it mean that age will be returned as a const?
  3. What happens if I declare int hisAge as not being a const?

Thanks in advance.

2 Answers

There are two separate questions here: const and constexpr.

Let's start with const, stripping out the constexpr.

class Human
{
    int age;

public:
    Human(int humansAge) : age(humansAge) {}
    int GetAge() const { return age; }
};

int main(int argc, char const *argv[])
{
    Human somePerson(15);
    const int hisAge = somePerson.GetAge();

    return 0;
}

The const on GetAge() declares that calling GetAge() will not change the state of the object. Thus if we tried to write:

int GetAge() const { return ++age; }

it would cause a compilation error, which would not be there without the const.

The const on hisAge:

const int hisAge = ...

simply says that hisAge can't be changed after it's been initialized, so a subsequent

hisAge = 50;

would be illegal.

However, all these are runtime constants. Although we've initialized human with a hard-coded 15, this would equally have worked with a value read in from the user or a file.

If we reintroduce all the constexpr keywords, it means we now have compile-time constants. We can have multiple humans with different ages, but all the ages must be available at compile time, i.e. hard-coded.

1 . The constexpr specifier declares that it is possible to evaluate the value of the function or variable at compile time. -- cppreference.

I'd say it does nothing in your example.


2 . constexpr int GetAge() const { return age; }

that const means something like this is const Human (const Human this <=> const int x)


3 . What happens if I declare int hisAge as not being a const?

It'd change nothing.


const is almost a hint, it helps you (programmer) write const-correctness code, stop you from unintended modification of state. It may change where the variable locates or some compiler optimization, but you'd probably not notice the difference.

Related