Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

argument's default value base on others

i want to achieve a class like this:

class A{
    int a;
    int b;
    int c;
    A():a(),b(),c(){};
    A(int ia,int ib,int ic=ia+ib):a(ia),b(ib),c(ic){};  //this is what i need
};

I want the ic's default value is caculated based on the ia and ib, the code here will get error when being compiled.

I wonder if there's a way to get something like this.

thanks.

like image 672
Detective King Avatar asked Sep 27 '13 05:09

Detective King


People also ask

When can any argument have a default value?

The default constructor with argument has a default parameter x, which has been assigned a value of 0. Key Points: Default arguments are different from constant arguments as constant arguments can't be changed whereas default arguments can be overwritten if required.

Which argument is an argument that assumes a default value?

Python allows function arguments to have default values. If the function is called without the argument, the argument gets its default value.

What are default arguments explain with example?

A default argument is a value in the function declaration automatically assigned by the compiler if the calling function does not pass any value to that argument.


1 Answers

Just add another constructor overload:

A(int ia, int ib)
  : a(ia), b(ib), c(ia + ib) {}

A(int ia, int ib, int ic)
  : a(ia), b(ib), c(ic) {}

For more complex initialisation, you can avoid repetition using a C++11 delegating constructor:

A(int ia, int ib)
  : A(ia, ib, ia + ib) {}

A(int ia, int ib, int ic)
  : a(ia), b(ib), c(ic) {}
like image 53
Jon Purdy Avatar answered Oct 19 '22 23:10

Jon Purdy