How to initialize an array in this constructor?

Asked

Viewed 350 times

4

I’m trying to initialize a array with 0, however the compiler is generating error, I know I can initialize as well:

Constructor() : Value1(0), Value2(0), Initialized(false), vSh(false)
{
    Name[100] = { 0 };  
}

However, I believe that this would be a bad practice, I believe that there must be some other way to boot in the following way:

class Constructor
{
private:
    char        Name[100];
    int         Value1, Value2;
    bool        Initialized;
    short       vSh;
public:
    Constructor() : Value1(0), Value2(0), Initialized(false), vSh(false), Name(0) {}
}

1 answer

4


Use string and be happy, it’s much more C++.

If you still want to use this form you will have to live with this limitation or initialize directly on the object:

char Name[100] = { 0 };

I put in the Github for future reference.

You can do the same with other members.

  • I could use string, but it’s not as fast compared to a char array, and I need to have an extremely fast program, any less millisecond makes a difference to my program.

  • Not always what seems fast is in fact. Even the greatest experts err in these assumptions. Who needs speed does not initialize limbs, especially long unless with real data. It also hardly creates a structure that wastes memory and harms cache, and perhaps creates overhead in use because it’s too big.

  • Why can’t you initialize limbs when you need speed, it gets in the way?

  • Of course, any operation takes time.

  • Even so, I believe that using string could be worse in the question of performance, thanks for replying my questions.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.