2
#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

6
  • 3
    "can't compile" - tell us the full error message. Commented May 3, 2018 at 3:47
  • 1
    Which versions of the compilers? What version of C++? Commented May 3, 2018 at 3:48
  • @JohnZwinck sorry, now I add a picture about the error. Commented May 3, 2018 at 3:52
  • 1
    Your image of text isn't very helpful. It can't be read aloud or copied into an editor, and it doesn't index very well, meaning that other users with the same problem are less likely to find the answer here. Please edit your post to incorporate the relevant text directly (preferably using copy+paste to avoid transcription errors). Commented May 3, 2018 at 14:25
  • 1
    I thought you said there were error messages in them? If so, they should be in the question (as text) instead of the images. Commented May 4, 2018 at 7:30

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

6 Comments

Sure, but making a non-const would make the constructor etc not be run at compile time. Kind of feels like the point of this.
but constexpr memeber function is implictly const.
@Rick No, it does not. constexpr int area() const notice the second const.
Yes, I am reading C++ Primer and it's C++11 I think. But I still don't understand why I can compiler this with g++ and I think my code is right.
@Rick When compiling with g++ use the command -std=c++11 to compile in C++11 mode. godbolt.org/g/DZ5x2Q
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.