Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C++ Default Argument using Default Constructor to instantiate

Is it possible to have a function that takes a reference to an argument that has a default, where the default is instantiated using its default constructor?

For example:

void g(Foo &f = Foo()) {}

This does not work, but I feel that it conveys my intention quite clearly.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

References to non-const cannot bind to temporary values, and Foo() is a temporary Foo object.

If you don’t need to modify the passed object, then you can make f a reference to const:

void g(const Foo& f = Foo()) {}

If you do modify the passed reference, then using a temporary doesn’t make much sense, since you’ll would be modifying an object that would go out of scope as soon as the function returns.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading