5

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.

TemplateRex
  • 69,038
  • 19
  • 164
  • 304
Detective King
  • 605
  • 1
  • 7
  • 14

2 Answers2

14

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) {}
Jon Purdy
  • 53,300
  • 8
  • 96
  • 166
0

You can simply build a default constructor with the required values or simply overload by adding another constructor. The values will be assigned after you've executed it.Something like..

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

Read this link if you need further help in setting up a default constructor.

kotAPI
  • 387
  • 1
  • 7
  • 20