Reputation: 15
As you can see, in the "Demo" class I declared "id". But I can't initialize it in the next line (I know, I could have done this in the same line, but still). I can do this same exact thing in case of "a" in the main function. Why???
#include <iostream>
using namespace std;
class Demo {
public:
int id;
id = 90;
int setID(int x)
{
id = x;
}
};
int main() {
int a;
a = 90;
Demo d;
d.setID(50);
cout<<a<<endl;
return 0;
}
Upvotes: 0
Views: 412
Reputation: 119382
A function body is a sequence of statements. A class body is a sequence of member declarations. Most kinds of statements can't go inside a class body, because they're not valid member declarations. You can only put "runnable code" inside a class if it's nested inside a function.
If there's a piece of code you want to have run every time a class is instantiated, put it in the constructor. If there's a piece of code you want to have run only once, when the class is defined, there's no mechanism for doing that in C++.
Upvotes: 3
Reputation: 21808
Because this is how the language works. main
is a function. Inside a function commands get executed one by one:
1) Create variable a
of type int
.
2) Assign value of 90 to a
3) Create object d
of type Demo
and so on.
But class Demo {
public:
int id;
int setID(int x)
{
id = x;
}
};
is not a function. It is a declaration of a class. It is nothing more than description of an entity. You cannot execute commands inside a description. You can say "this class has int a
" and that's it
Upvotes: 2