Calling two constructors with one object?

Is it possible to instantiate one class object that calls two constructors?

I have a one-parameter constructor and a two-parameter constructor. I would like the call the first one, and then the second one as soon as I make the object. Is this possible in c++?

Are you talking about something like this?
1
2
3
4
5
class C
{
    C(stuff);
    C(stuff2, stuff3);
}


And then somewhere in another file, you call both of them at the same time? As far as I can see, I don't think that's possible, for what I think is a similar reason to having two functions in two different libraries with identical names. It'd be ambiguous. The compiler wouldn't know which one to do processes with.

The only way the compiler would know is dependent on the number of parameters you gave to your constructor, and if you're using VS or Codeblocks (I've never used MinGW or Turbo so I don't know if those do it), there's the fancy little list that pops up bolding whatever parameter you're on if you have two same-name functions with different parameter lists.
Hi,

No. The purpose of a ctor is to create an object.

Why would you want to do that anyway?

I am guessing a bit as to what you are trying to achieve here. For what you have in your second ctor, make that a private function instead and have the first ctor call that function.

If you still need both ctor's, then consider factoring out the code that is common to both ctor's and putting it into a private function.

Good Luck !!

Edit: this is called a Delegating constructor.
Last edited on
Are you talking about something like that
1
2
3
4
5
6
7
8
9
10
11
12
struct Number
{
    Number(int n) : i(n) {} //If user provides number, store it
    Number() : Number(42) {} //Else we delegate initialization to other constructor
    int i;
}

int main()
{
    Number n;
    assert(n.i == 42);
}
Thank you everyone for your replies. I just realized I DON'T need to call both constructors with one object. I misunderstood the assignment.

But thank you anyways. I still learned a lot from your replies.


Topic archived. No new replies allowed.