CLASSES - ISO C++ forbids in-class initialization of non-const static member 'pi'

Mar 17, 2015 at 6:20pm
Hello I have a little problem I don't undestand what the problem is can someone explain to me?



error: ISO C++ forbids initialization of member `pi'
error: making `pi' static|
ISO C++ forbids in-class initialization of non-const static member 'pi'

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include <iostream>

using namespace std;

class circle
{
    public:
             double pi=3.14;
        double s(double r)
        {
            double S;
            S=2*r*pi;
            return S;
        }
        double p(double r)
        {
            double P;
            P=r*r*pi;
            return P;
        }
};

int main()
{
    double r;
    cout<<"Enter the radius"<<endl;
    cin>>r;
    circle k;
    k.p(r);
    k.s(r);
    return 0;
}
Last edited on Mar 17, 2015 at 6:27pm
Mar 17, 2015 at 6:34pm
The reason you're getting the error I believe is because you are initializing a variable in your class. double pi=3.14;

As far as I know, you werent able to do that before c++11. But since c++11 you can do it no problem. I just tested your program and it runs fine for me. Are you like using a really old version of c++?

Maybe someone else can come and explain. Either way, how to get around this is to just create the variable pi, then initialize it in the constructor.
Mar 17, 2015 at 8:04pm
Prior to C++ 11, in order to initialize a variable in your class, you needed to declare it as const static - denoting that it is [1] immutable (const) and [2] shared between all instantiated objects of that class (static).

Post C++ 11, the compiler should take care of that detail for you. However, if you're using an older compiler, it may complain. Specifically, with g++, you have to include the -std=c++11 flag in the compile command, eg:

g++ -std=c++11 source.cpp -o source

If you're using an up-to-date compiler like VS, it should compile without complaint.

Last edited on Mar 17, 2015 at 8:05pm
Topic archived. No new replies allowed.