1

Is there any way to use C#-like constructor syntax in C++ when you have multiple constructors for the same class, for example:

class complex
{
public:
    double re, im;

    complex(double r, double i)
    {
        re = r;
        im = i;
    }

    complex():this(0.0d,0.0d) 
    {

    }
};

this particular example didn't seem to work, but is there any ?

Ilia
  • 341
  • 3
  • 12
  • yes, you can forward-call different constructor, you refer to it with the class' name, not this – Creris Sep 05 '15 at 21:15
  • 1
    The same question was answered [here](http://stackoverflow.com/questions/308276/call-constructor-from-constructor-in-c) – Estiny Sep 05 '15 at 21:19

2 Answers2

4

In C++11 you can do this:

class complex {
public:
    double re, im;

    complex(double r, double i) 
      : re(r), im(i) {

    }

    complex()
      : complex(0.0d, 0.0d) {

    }
};

If for some reason you can't use C++11 and you need a case this simple, you can use default arguments:

class complex {
public:
    double re, im;

    complex(double r = 0.0, double i = 0.0) 
      : re(r), im(i) {

    }
};

which of course has a downside: you can (mistakenly) supply only some of arguments, like this: complex a(1.0).

dreamzor
  • 5,795
  • 4
  • 41
  • 61
1

From C++11 there is constructor delegation feature.

You can do:

class A{
public:    
   A(): A(0){ cout << "In A()" << endl;}
   A(int i): A(i, 0){cout << "In A(int i)" << endl;}
   A(int i, int j){
      num1=i;
      num2=j;
      average=(num1+num2)/2;
      cout << "In A(int i, int j)" << endl;}  
private:
   int num1;
   int num2;
   int average;
};

int main(){
   class A a;
   return 0;
}
CyberGuy
  • 2,783
  • 1
  • 21
  • 31