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 ?

2
  • yes, you can forward-call different constructor, you refer to it with the class' name, not this Commented Sep 5, 2015 at 21:15
  • 1
    The same question was answered here Commented Sep 5, 2015 at 21:19

2 Answers 2

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).

Sign up to request clarification or add additional context in comments.

Comments

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;
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.