I have a class Foo that contain a variable int bar and I want to make 255 as an initial value for bar like this.
Foo foo1, foo2;
cout << foo1.bar << "," << foo2.bar; //255,255
foo1.bar = 254;
cout << foo1.bar << "," << foo2.bar; //254,255
As I know, there is lot of way to do this! For example:
//Use int bar = 255
class Foo {
public:
int bar = 255;
Foo() {}
};
//Use bar(255) or bar = 255 on constructor
class Foo {
public:
int bar;
Foo() : bar(255) {}
//Or Foo() { bar = 255; }
};
So my question is, which way is better in my case? (Or it was just the same?)
I need this for my project because there is a lot of very big class that contain over 100 variables (some are over 300) so I worry about the performance. Thanks!
>Solution :
If you declare one constructor, then int bar = 255; is equivalent to : bar(255).
The only difference between them is that the former applies to any constructor you provide that doesn’t have an initialiser for bar.
There is a variation on your first case:
class Foo {
public:
int bar = 255;
// among other things, implicit default constructor is defined
};
C++ is defined by observable behaviour, so all of them, even { bar = 255; } can have the same implementation in object code.