define a class with variables in one line?

basically what I want is:
1
2
3
4
5
6
7
8
9
10
class test
{
     int var1;
     int var2;
};

int main
{
     test v = 2/*var1*/, 5/*var2*/;
}

is there any similar way to do that? So that I don't have to go:
1
2
3
4
5
6
7
8
9
10
11
12
class test
{
     int var1;
     int var2;
};

int main
{
     test v;
     v.var1 = 2;
     v.var2 = 5;
}
yes:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class test
{
public:  // These are the elements available outside of the class
    test(int _v1, int _v2) // This is a constructor, it initializes whatever you like when a class is made.
    {
        var1 = _v1;
        var2 = _v2;
    }

    int var1;
    int var2;
}

int main()
{
    test v(2,5);
}


Read up on constructors here:
http://www.cplusplus.com/doc/tutorial/classes/

Another shorthand version of the same code uses initialization lists:
1
2
3
4
5
6
7
8
9
10
11
12
class test
{
public:
    test() : var1(int _v1), var2(int _v2) {}
    int var1;
    int var2;
}

int main()
{
    test v(2,5);
}
Last edited on
I should also mention that lines 10 and 11 of your second block of code will cause a compiler error. This is because var1 and var2 are private by default, unless specified otherwise. This is the major difference between a class and a struct. You need to make them public by including that keyword in the class.
Thanks.
Oh, yeah. It was just pseudocode, I wasn't really paying too much attention. :P Thanks, anyway, though.
If you are using a structure (as in a class with only public variables and no methods like you first posted) you can do it like this too, although this is not used much because it's just shorthand (i.e. lazy) for an initializer list defined on the constructor like above. Anyway, like this:
1
2
3
4
5
6
7
8
9
10
11
//...
struct S {
	char c;
	int i;
};

int main() {
	S s = {'S', 4};
	//...
}
//... 
Stewbond's second code block is wrong. This should work better
1
2
3
4
5
6
7
8
9
10
11
12
class test
{
public:
    test(int _v1, int _v2) : var1(_v1), var2(_v2) {}
    int var1;
    int var2;
};

int main()
{
    test v(2,5);
}
Topic archived. No new replies allowed.