Rick
Rick

Reputation: 7516

literal class compile error with constexpr constructor and function (differ vc, g++)

#include <iostream>
#include <string>
using namespace std;

class A {
public:
    constexpr A() {}
    constexpr int area() {
        return 12;
    }
private:
//  constexpr int h = 3;
//  constexpr int w = 4;
};
int main()
{
    constexpr A a;
    constexpr int j = a.area();
    cout << j << endl;

}

Why the code above can't compile with MSVC compiler while works with g++? Isn't MSVC not as strict as other compilers? The difference results between MSVC and g++ is sometimes confusing. Which compiler should I rely on, any tips btw?

enter image description here enter image description here

Upvotes: 2

Views: 167

Answers (1)

Ivaylo Valchev
Ivaylo Valchev

Reputation: 10425

The problem is that a constexpr object implies const, which means you cannot call area as it is a non-const function. Mark area as const and that's it.

Alternatively, making a non-const will allow you to keep area non-const, which whilst odd, it's valid C++.

EDIT. Perhaps you are using C++14 or above. Your impression that a constexpr function implies const is a C++11 feature that was changed in later standards.

Upvotes: 4

Related Questions