c++arraysclass-constructorsin-class-initialization

c++ initialize class member variable depends on other member variable


Basically, a non-static member theta which initialize by another class member but well initialized. Then valley_max initialized by theta as you can see. Right now everything works fine. Then I want to initialize a array whose bound is valley_max. First, the I got error :

invalid use of non-static data member

Then I add static const int valley_max as you can see. But I got error like:

array bound is not an integer constant before ']' token

I just wondering if I can initialize the array whose bound initialized by a member variable which initialized by another member variables.
Thanks for your help.

AP_Tmxk_VFH.cpp

AP_Tmxk_VFH::AP_Tmxk_VFH() :
    l(5),
    threshold(5),
    safe_space(0.7),
    detected_range(2.5),
    theta(degrees(acos(1-sq(safe_space)/(2*sq(detected_range))))),
    valley_max(round_float(180.0/theta)),
    valley_count(0),
{
}

AP_Tmxk_VFH.h

class AP_Tmxk_VFH {
privte:
       int l;
       int threshold;
       int safe_space;
       int theta;
       int detected_range;
       static const int valley_max ;
       struct{

         bool inside_valley  = false;
         uint16_t up_bound   = 0;  
         uint16_t down_bound = 0; 
   }valley[valley_max];
}

Solution

  • Your specific issue is due to the fact that variable length arrays are not supported in C++. Consider using a std::vector or another C++ standard library container instead.

    But you have further problems (which in my opinion makes your question interesting): the order of member initialisation is the order they appear in the class definition, not the order they appear in the initialisation.

    For example, in your case theta is initialised before detected_range, and since the latter is not initialised at the point you use it in the evaluation of theta, the behaviour of your code is undefined!

    In your case, unless you need the members to be const, I'd initialise the ones that are not set to literals in the constructor body if I were you.