Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding CPP specific Class declaration and resulting error

Tags:

c++

My CPP understanding is not good enough to understand the following Class declaration

#define Default_n_datapoints 10

class MeanAngle {
   public:
       MeanAngle(std::size_t a_nDataPoints = Default_n_datapoints) : 
         NDATAPOINTS (a_nDataPoints) {};
       virtual ~MeanAngle();
       virtual void AddSample(const float a_fSample);
       virtual float GetAverage() const;
  protected:
       const std::size_t NDATAPOINTS;
   private:
       float ring[NDATAPOINTS];
       uint8_t i;
   };

and in particular: If NDATAPOINTS is const, why can't I use it dimensioning ring[]? ring[NDATAPOINTS] gives me an error:

A non-static member reference must be relative to a specific object

How should I correct the declaration? What I want is that the initialisation parameter a_nDataPoints to be used as dimension in the ring buffer.

like image 261
hans Avatar asked Jan 25 '26 14:01

hans


1 Answers

A specified array size must be a compile-time constant. That is, its value must be known at compile time. If you pretend that you are a C++ compiler, yourself, look at this code, and attempt to figure out what actual, integer, value NDATAPOINTS is, you will fall far short of your lofty goals.

The only thing that const gives you is that a const value is a run-time constant. It never changes once it exists. That's not the same thing as a compile-time constant. A compile-time constant would be a constexpr.

like image 177
Sam Varshavchik Avatar answered Jan 27 '26 03:01

Sam Varshavchik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!