1
class draw
{
    draw(circle i)
    {
        // draw a circle;
    }

    draw(circle i, circle j)
    {
        draw(i);
        draw(j);
    }
}

Can I call another overloaded constructor of the same class in C++ even if using template?

Kevin Dong
  • 5,001
  • 9
  • 29
  • 62

1 Answers1

2

No, in C++ you cannot have one constructor directly call another (well, at least not more than once). However, you can have each constructor call a third method that performs actual work.

class draw
{
    draw(circle i)
    {
        do_draw(i);
    }

    draw(circle i, circle j)
    {
        do_draw(i);
        do_draw(j);
    }

    void do_draw(circle c)
    {
        // draw a circle;
    }
}
Greg Hewgill
  • 951,095
  • 183
  • 1,149
  • 1,285
  • Well didn't c++11 (or at least c++14) introduced calling other constructors in the member initializer list? – πάντα ῥεῖ Jun 02 '15 at 04:18
  • 1
    Yes, C++11 allows a constructor to call another constructor of the same class in the initializer list. It is called [delegating constructors](http://www.stroustrup.com/C++11FAQ.html#delegating-ctor). – Remy Lebeau Jun 02 '15 at 04:18
  • That's right, but you can only call a delegated constructor once, not more than once as this question suggests. – Greg Hewgill Jun 02 '15 at 04:21
  • @GregHewgill How the question suggests, that the constructor should be called _more than once_? Can you elaborate about an actually applicable solution regarding the current standard please? – πάντα ῥεῖ Jun 02 '15 at 04:24
  • @πάνταῥεῖ: What? I'm not talking about any standard. I'm observing that the OP's two-argument constructor actually wants to draw two circles. If there is a single-argument constructor that draws one circle, you can't call that constructor twice to draw two different circles. One would have to create a third method as I have suggested in my answer. – Greg Hewgill Jun 02 '15 at 04:28