Question

I am in the process of learning c++. I have a struct like this:

struct Info {

const Long rate;
A* ptr;

}

I have a constructor which takes all the arguments as its parameters to initialize the struct. However, this struct is part of another class which will be serialized using boost serialization. In order to serialize that class I would need a default constructor for this struct. However, when I try to write a default constructor such as

Info () {
}

I get an error C2758 that the member rate should be initialized in the constructor. How to get a default constructor for such a struct which I can use to serialize my class.

Was it helpful?

Solution

You need to initialize the constant value, so:

Info () : rate(0) {
}

OTHER TIPS

The error is probably due to the fact that your Long class does not have a default constructor either.

There are two ways of fixing this:

  • Add a default constructor to Long, or
  • Add rate to the initialization list of Info's constructor.

You can see the msdn documentation for C2758 for a description of the error.

In basic term's, a const variable must be initialised in all constructors. The compiler enforces that any built in type or pointer member that is const must be initialised when the object is constructed, as you won't get a chance to give it a meaningful value after construction ( if you could change it after it was created, how is it const ? ).

Also, as a general rule of thumb, it is always a good idea to initialise members that don't have a default constructor ( built in types, pointers, and objects without default constructors ) to something, in all your class constructors. Otherwise they will either be initialised to some random value ( primitives or pointers ), or you will get a compile error ( objects without default constructors ).

Info()
 : rate(0)
 , ptr(nullptr)
{
}

If you are assigning values to some of your parameters from constructor arguments, don't forget to assign a value to the other members as well.

Info( Long rate)
 : rate( rate )
 , ptr(nullptr)
{
}

try this :

   struct Info {
      const Long rate;
      A* ptr;
      Info():rate(0){} // as Matthew guessed, call the correct Long constructor
                       // or define a default constructor for Long

   };
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top