If the data member of a class is public, isn't it syntactically correct to assign value to it anywhere after the class declaration?
I am trying following code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
#include <iostream>
usingnamespace std;
class rect
{
public:
int x,y;
};
class rect obj;
obj.x=1;
int main()
{
return 0;
}
class_without_functions.cpp:13:1: error: ‘obj’ does not name a type
Program doesn't give error while creating objects. But I cannot assign value to x.
Am I not putting it in a correct syntax? Kindly help
I believe the problem is that the 'code' outside of main does not get 'executed'. The assignment of 1 to the variable obj.x would require that the line of code be executed.
This is a statement: obj.x = 1;
Changing it to a default constructor seems to work. But it also seems to violate your "class without functions" idea because the default constructor looks like a function.
The following code compiles and executes:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
#include <iostream>
usingnamespace std;
class rect
{
public:
int x,y;
rect(int X, int Y) {x = X; y = Y;}
};
class rect obj(1,0);
int main()
{
return 0;
}
If the data member of a class is public, isn't it syntactically correct to assign value to it anywhere after the class declaration?
No.
Constructors and destructors are called automatically, and will be called outside a function for global variables of that type. But, generally speaking, code is executed within a function.
@bradw and kbw - Oh ! You are right. I was just trying to experiment with these things :D
Was so behind assigning value to that member that I literally forgot basics of a code execution.
Thanks for the help :)