user1607425
user1607425

Reputation:

Why is the initializion of class members not allowed outside of the constructors?

In other words, why does the compiler complain about things like this:

class Integer {
  int i = 3;
};

Although this is a really silly example, there are many cases in which classes have members which can be by default initialized to some value (for example some internal counter which always is default initialized to zero). What is the reason for forbidding these default initializations outside of the class constructors?

Upvotes: 2

Views: 123

Answers (2)

huseyin tugrul buyukisik
huseyin tugrul buyukisik

Reputation: 11926

Because there are constructors.

class InTeGeR
{
    Public:
           int i;
           InTeGeR()
            {
                i=3;
            }
 }

In presence of out-constructor initialization:

class InTeGeR
{
    Public:
           int i=3;
           InTeGeR()
            {
                i=5;
            }
            //now, i could be 3 or 5. Which one? 
            int j=i+1;
            //is j 4 or 6? Very confusing
 }

Upvotes: 1

bstamour
bstamour

Reputation: 7776

As said in the comments, in C++11 you actually can do it like you showed. It's still illegal in C++98/C++03 however.

Edit: To answer your question however: I don't know :p maybe the language designers didn't think anyone would want to do that at the time of publishing C++98. In any case you certainly can do it now with C++11.

Upvotes: 0

Related Questions