user1905552
user1905552

Reputation: 101

How to set a preceding function parameter to its default in c++?

Apologies if this basic question has already been answered. What would I put inside the brackets of print() so that the first parameter is left to the default value but the following parameters are given new values of 1 and 2? I know I can literally put 0 in there but is there a way for it go to a default?

#include<iostream>

using namespace std;

void printer(int a=0, int b=0, int c=0){
 cout << a << endl;
 cout << b << endl;
 cout << c << endl;
}

int main(){

//leave a=0 and replace both b and c 
printer(/*?*/,1,2);

 return 0;
}

Upvotes: 3

Views: 133

Answers (6)

Alexander Shukaev
Alexander Shukaev

Reputation: 17021

You could utilize function overloading to achieve what you want:

void printer(int a, int b, int c) {
  cout << a << endl;
  cout << b << endl;
  cout << c << endl;
}

void printer() {
  printer(0, 0, 0);
}

void printer(int b = 0, int c = 0) {
  printer(0, b, c);
}

int main(){
  // leave a = 0 and replace both b and c 
  printer(1, 2);

  return 0;
}

Upvotes: 0

Vaughn Cato
Vaughn Cato

Reputation: 64308

You can't do exactly that, but one approach to this problem is to pass a struct with your parameters:

struct PrinterParams {
  int a,b,c;
  PrinterParams() : a(0), b(0), c(0) { }
};

void printer(int a, int b, int c) {
 cout << a << endl;
 cout << b << endl;
 cout << c << endl;
}

void printer(const PrinterParams &params) {
  printer(params.a,params.b,params.c);
}


int main(){
  PrinterParams params;

  params.b = 1;
  params.c = 2;
  printer(params);

 return 0;
}

Upvotes: 0

TieDad
TieDad

Reputation: 9889

You cannot do that, it's not allowed. Only right most parameters could be omitted.

Upvotes: 3

David G
David G

Reputation: 96800

Use std::placeholders::N to delegate the arguments to specify to the returned function object from std::bind.

int main()
{
   auto f = std::bind(printer, 0, std::placeholders::_1, std::placeholders::_2);

   f(4, 5);
}

Live Demo

Upvotes: 2

4pie0
4pie0

Reputation: 29724

all parameters after first default are default. You can get what you want in this particular case changing the sequence:

void printer(int b=0, int c=0,int a=0){
 cout << a << endl;
 cout << b << endl;
 cout << c << endl;
}

//leave a=0 and replace both b and c 
printer(1,2);

output:

0

1

2

Upvotes: 2

shivakumar
shivakumar

Reputation: 3397

Default parameter list is right associative. So its not possible to ommit first parameter list.

Upvotes: 2

Related Questions