Why does not in-class “const int m = 2;” compile (C2864)?


This doesn’t compile (error C2864).

struct CMyClass
{
    const int m = 2;
};

It requires ‘static’. But why?

IMO, it’s because this brings up a problem to the compiler.
The compiler has to inject code into the constructor to initialize m, just as injecting a base constructor call to sub constructor. By making m static, m is simply in the data section of the executable file.
In C++11, this piece of code is no longer an error.

Advertisements

Difference between this->CMyClass::CMyClass() and CMyClass()


Why does it have to be this complicated to call a constructor:

this->CMyClass::CMyClass();             instead of just  CMyClass();

See function f() in the following example.

struct CMyClass
{
	int mi;
	CMyClass()
	{
		printf("%d\n", mi);
	}
	void f()
	{
		this->CMyClass::CMyClass();
	}
};

void GeneralTest()
{
	CMyClass a;
	a.mi = 2;
	a.f();
}

In this->CMyClass::CMyClass();
‘this’ is required; Otherwise it creates a temporary object instead of calling constructor.
‘CMyClass::’ is required; otherwise CMyClass is interpreted as a type instead of a constructor.

The difference between with ‘this’ and without ‘this’ can be tested by GeneralTest(); just watch the output.
(This code runs as expected on Visual Studio 2010, which has some C++11 features built in)

011 is less than 10? Yes.


Have you used octal numbers? If you never did, here is how they are represented.

void main()
{
	if(011 < 10)
	    printf("011 < 10");
}

Is it possible that x == x – 1?


This happened in my real product when clients’ balance changed as little as 1 Japanese cent.

void GeneralTest()
{
 float x = 1e30; //big number, 30 zeros following 1
 if(x == x - 1)
  printf("x == x - 1");
}

I try to avoid floating point numbers because not only they are slow, but also they’re not accurate.