Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Optional argument, by reference, for polymorphic method?

Tags:

c++

I have a polymorphic method hierarchy like this:

void func(double x, const std::string& s) = 0;

and I want to pass an "optional" argument which is modified within the method:

void func(double x, const std::string& s, uint64_t& i = 0) = 0;

but I receive errors that my reference was not initialised.

What is the best way to implement the above?

like image 485
mezamorphic Avatar asked Jun 16 '26 11:06

mezamorphic


2 Answers

uint64_t& is an L-Value reference, and can therefore not bind to an R-Value, like the literal you provide as default argument. You must provide an L-Value as default.

One option is to define a dummy object that you pass as default, e.g.:

static uint64_t dummy_default_value = 0;
void func(double x, const std::string& s, uint64_t& i = dummy_default_value ) = 0;
like image 71
king_nak Avatar answered Jun 18 '26 01:06

king_nak


I would avoid default parameter for virtual method (see good-practice-default-arguments-for-pure-virtual-method), so just add an extra overload

virtual void func(double x, const std::string& s, uint64_t& i) = 0;
void func(double x, const std::string& s) { int i; func(x, s, i) };

If you really want to keep default argument, you may use boost::optional:

virtual void func(double x,
                  const std::string& s,
                  boost::optional<uint64_t&> i = boost::none) = 0;
like image 45
Jarod42 Avatar answered Jun 18 '26 02:06

Jarod42



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!