meWantToLearn
meWantToLearn

Reputation: 1700

c++ constants how to make them work

So far I have used DEFINE to declare my constants. and it works perfectly fine.

I am trying to use the c++ const keyword in my classes but it gives compile time error

Header

  class User{

  public:
     User::User();
  protected:
       const float DATA_Z;

   }

.CPP

 User::User(){

         DATA_Z = 0.0023f;

  }

this is the error it generates

Error 3 error C2758: 'User::DATA_Z ' : must be initialized in constructor base/member initializer list

How can I assign a data to it, and how can I use them in my class.

Upvotes: 0

Views: 67

Answers (4)

Pete Becker
Pete Becker

Reputation: 76245

To simply replace manifest constants defined with #define, write global consts:

#define DATA_Z 0.0023f

becomes

const float DATA_Z = 0.0023f;

Putting the constants into the class means you can have a different value in each object, which is why the other answers tell you to initialize it in the constructor. That's a legitimate design decision, but it's different from defining the value as a macro.

Upvotes: 2

Kaustav Ray
Kaustav Ray

Reputation: 754

The following code helps you to pass any value to initialize the DATA_Z:

`
   class User{
         public:
            User::User(float data=0):DATA_Z(data){}; // here `data` is a local parameter to receive            the assigned value.
        protected:
           const float DATA_Z;
   }
`

Upvotes: 1

Joe Z
Joe Z

Reputation: 17936

You want to do this instead:

User::User() : DATA_Z(0.0023f) 
{
    // body of constructor
}

Constant members need to be initialized in the initializer list, because they cannot be assigned directly. The same is also true for members that are reference-type, because you cannot change the referent of a reference variable.

Upvotes: 4

awesoon
awesoon

Reputation: 33661

The error message is pretty clear. Move assignment into initializer list:

User::User(): DATA_Z(0.0023f)
{

}

Upvotes: 5

Related Questions