Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Which way is better for declaring class variable with constants initial value?

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!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading