Horst Walter
Horst Walter

Reputation: 14081

Avoid default constructor for member variable

I have a class with a member variable of another class:

class MeasurementUnit {
private:
    MeasurementMultiplier _multiplier;

Actually I would not need a default constructor for MeasurementMultiplier, because actually I will initialize with parameters MeasurementMultiplier(a,b,c), and I would - but can't directly:

C2864: 'MeasurementUnit::_multiplier' :
only static const integral data members can be initialized within a class

So I need the default constructor, without it does not compile error: C2512: 'MeasurementUnit' : no appropriate default constructor available

Can I avoid needing the default constructor?

Upvotes: 0

Views: 2984

Answers (2)

Daniel Frey
Daniel Frey

Reputation: 56863

In all constructors of your class MeasurementUnit, you need to initialize the member variable _multiplier in the initializer list. Example:

MeasurementUnit::MeasurementUnit()
  : _multiplier(1,2,3)
{}

Upvotes: 6

user1708860
user1708860

Reputation: 1753

Use MIL - Member Initialization List MIL

Upvotes: 1

Related Questions