INITIALISATION

why cant we initialise data members of class as shown.

class items{
private: int x=10; // why is this step wrong
int y;
};
It's only possible to initialize static, integral variables like that. To get some idea about why you can't initialize non-static members in this way, consider if you have more than one constructor:

1
2
3
4
5
6
7
class items {
private:
    int x;
public:
    items() : x(10) {}
    items(int v) : x(v) {} // initialize to something else here
};


The variable x is initialized differently depending on which constructor is called.
Topic archived. No new replies allowed.