Class member variable initialisation

Is it possible to initialize class member variables in their definition statement instead of using a constructor?

Is the code bellow correct?

class rectangle
{
float a=0;
float b=0;
public:
string color="Red";
...
};

Which C++ Standard allows it?
It's correct.

http://ideone.com/k7O1nV
closed account (zb0S216C)
Yes, it's correct, but only if your compiler supports such a feature. If you didn't know, C++'03 doesn't allow such initialisation, but C++'11 does. If you want to retain compatibility with C++'03 compilers, use the constructor's initialiser-list.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#if( __cplusplus == 199711L )
    // C++'03 support.
    class Sample
    {
        public:
            Sample( )
              : Member( 0 )
            { }
 
        private:
            int Member;
    }; 
#elif( __cplusplus == 201103L )
    // C++'11 support.
    class Sample
    {
        public:
            Sample( );
 
        private:
            int Member = 0;
    }; 
#endif 


Wazzak
Topic archived. No new replies allowed.