0

First question:-

why this is must have to be defined static data members outside of the class and why not this same concept follows in static constant data members?

Example for static data members:-

#include<iostream>
using namespace std;
class game
{
    static int num;
    int i;
    public:
    void foo()
    {   
        cout<<endl<<num<<endl;
    }
};
int game::num=0;
int main()
{
    game g;
    g.foo();
    return(0);
}

Example for static constant data members:-

#include<iostream>
using namespace std;
class game
{
    static const int num; 
    int i;
    public:
    void foo()
    {   
        cout<<endl<<num<<endl;
    }
};
int game::num=0; \\error why ?
int main()
{
    game g;
    g.foo();
    return(0);
}

second question:-

Static constant data members initialization is allowed only for integral types why not for strings ?

#include<iostream>
using namespace std;
class game
{
    static const char name[10]="vikas"; \\ error why ?
    int i;
    public:
    void foo()
    {   
        cout<<endl<<name<<endl;
    }
};
int main()
{
    game g;
    g.foo();
    return(0);
}
Vikas Verma
  • 3,626
  • 6
  • 27
  • 40
  • 1
    `int game::num=0; //error why ?` -> because you declared `game::num` with the type `const int`, not just `int`. *"Static constant data members initialization is allowed only for integral types why not for strings ?"* Some of those restrictions have been lifted with C++11's `constexpr`. – dyp Jan 21 '14 at 18:24
  • 1
    As for the remaining question *"why do static data members have to be defined outside the class"*, you'll find a lot of duplicates on StackOverflow; for example [this one](http://stackoverflow.com/questions/9786029/why-we-have-to-define-a-const-static-member-that-is-initialized-within-a-class?rq=1) which also appears (appeared) in the "Related" side bar. – dyp Jan 21 '14 at 18:26

0 Answers0