Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simplest way to initialize multiple related const properties in a constructor?

When multiple const properties of a C++ class depend on some intermediate calculation, what is the simplest way to initialize them?

For example, how do I correct the constructor for the class below?

class MyClass {
public:
    const int a;
    const int b;

    MyClass() {
        int relatedVariable = rand() % 250;
        a = relatedVariable % 100;
        b = abs(relatedVariable - 150);
    }
};
like image 424
Victor Lyuboslavsky Avatar asked Mar 20 '13 22:03

Victor Lyuboslavsky


People also ask

How do I initialize all const data?

To initialize the const value using constructor, we have to use the initialize list. This initializer list is used to initialize the data member of a class. The list of members, that will be initialized, will be present after the constructor after colon. members will be separated using comma.

Can you initialize a const variable?

A constant variable must be initialized at its declaration. To declare a constant variable in C++, the keyword const is written before the variable's data type.

Can constructors be declared const?

Constructors may be declared as inline , explicit , friend , or constexpr . A constructor can initialize an object that has been declared as const , volatile or const volatile . The object becomes const after the constructor completes.

Does const need to be initialized?

An initializer for a constant is required. You must specify its value in the same declaration.


2 Answers

This will kinda work for those of us who happen to prefer being less advanced in their coding:

class MyClass {
public:

    int iamStupid;      /* K.I.S.S. */

    const int a;
    const int b;

    MyClass()
      : iamStupid(rand() % 250)
      , a(iamStupid % 150)
      , b(abs(iamStupid - 150))
    {}
};

The additional member presents an unnecessary overhead — which may or may not be significant for the task at hand. OTOH, the code is simple.

Remember to declare iamStupid before a and b! (see comments)

like image 181
ulidtko Avatar answered Sep 20 '22 21:09

ulidtko


Here's a roundabout solution using delegating constructors:

class MyClass
{
    MyClass(int aa, int bb) : a(aa), b(bb) { }

    static MyClass Maker() { int x = /* ... */; return MyClass(x * 2, x * 3); }

    int const a;
    int const b;

public:
    MyClass(MyClass const &) = default;
    MyClass() : MyClass(Maker()) { }
};
like image 41
Kerrek SB Avatar answered Sep 21 '22 21:09

Kerrek SB