Sign in to follow this  

Constructor "Chains"

This topic is 3723 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I tried to find this out myself, but I know that "constructor chains" is not the correct term, and I don't know what to call it. Basically, in C#, if my class had multiple constructors with less and less arguments, I would use them like this:
MyClass(int arg1, int arg2)
{
}

MyClass(int arg1) : this(arg1, 0)
{
}

MyClass() : this(0, 0)
{
}

How can I do this sort of thing in C++?

Share this post


Link to post
Share on other sites
Quote:
Original post by Uphoreum
I tried to find this out myself, but I know that "constructor chains" is not the correct term, and I don't know what to call it.

Basically, in C#, if my class had multiple constructors with less and less arguments, I would use them like this:


*** Source Snippet Removed ***

How can I do this sort of thing in C++?
I don't know C# very well, but based on what you posted I'm guessing that you're looking for default arguments and/or overloaded constructors (the former most closely matches what you posted).

Share this post


Link to post
Share on other sites
C++ doesn't allow sibling constructor calls currently. There's a proposal for the next version of the standard that adds it, but that's not really much help right now.

Share this post


Link to post
Share on other sites
Default arguments often (but not always, depending on your needs) work. It appears it will for your example.

MyClass::MyClass(int arg1 = 0, int arg2 = 0)
{
}



If the body of the constructor is to be shared, you can sometimes get away with moving the code to a private "init" style member function called from each constructor.

Share this post


Link to post
Share on other sites

This topic is 3723 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this