2

I'd like to know if there's any possibility to create a constructor in C++ which uses for example float but this float isn't necessary. I mean:

Constructor:

Fruit::Fruit(float weight)
{
    weight = 1;
    this->setWeight(weight);
}

I need to do something like that using one constructor:

Fruit pear = Fruit(5);          - gives a pear with weight 5
Fruit strawberry = Fruit();     - gives a strawberry with default weight 1

2 Answers 2

5

Yes, this can be done by specifying the value with a = in the argument list:

Fruit::Fruit(float weight = 1)
{
    this->setWeight(weight);
}
Sign up to request clarification or add additional context in comments.

1 Comment

2

Use in-class initialization, which can significantly clean up code:

class Fruit {
public:

  Fruit() = default;
  Fruit(float weight) : weight_{weight} {}

  // ... other members

private:
  float weight_ { 1.0f };

};

This way, a default weight of '1' is automatically created if the default c'tor is called. This has the benefit of significantly cleaning up initialization lists in constructors. Consider what would happen if you had many class members that are default-initialized to garbage values (i.e. any of the built-in types). Then you would have to explicitly initialize them in the c'tor initializer lists, which gets cumbersome. With in-class initialization, you can do this at the member declaration site.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.