Syntax error warning for int constructor

This is as simple as it gets.

1
2
3
4
5
6
7
8
9
10
11
#ifndef TEST2_H_
#define TEST2_H_

class Test2 {
	public:
		Test2(short a);
	private:
		int i(-1);
		short j;
};
#endif 


1
2
3
4
5
6
7
8
9
/*
 * Test2.cpp
 *
 *  Created on: 25/09/2013
 *      Author: Temp
 */

#include "Test2.h"
Test2::Test2(short a):j(a) {}


However the line int i(-1) gives me a syntax error. As far as I could find out this SHOULD be legal. So am I missing some obvious mistake, or is this possibly a problem with Eclipse? I'm using Kepler along with the latest CDT and MinGW.
Hi there,

You are not allowed to initialize class members in their declaration (at least until c++11).
The way to go is to initialize i in the same place as you do j.

Test2::Test2(short a) : i(-1), j(a) {}

I believe in C++11 you are allowed to initialize non-static members in the class declaration, but your compiler has to support it, of course.

All the best,
NwN
Even in C++11, this would have to be brace-or-equal initializer (int i = -1; or int i{-1};) see: http://ideone.com/hQxkrn
Last edited on
Thanks Cubbi, you provided the solution! I did forget to mention that I have in fact told the compiler I'm programming by the C++11 standard. However when I've used int i = -1, the compiler has then complained about i being uninitialized when I use an initializer list for my constructor. I had the same problem with a boolean, and managed to fix that using boolean a(); so I assumed the same would work for an int, and that it had a constructor taking a variable.

So using the curly brackets is the solution that works for me, and now I have to try it on the boolean too. Thanks again, Cubbi.

Oh and thanks as well for introducing me to ideone.
Last edited on
Topic archived. No new replies allowed.