1

Possible Duplicate:
c++ call constructor from constructor

I have two constructors for the same class and I want one of the constructors to send data to the second constructor.

I know how to do it in C# but I'm new to C++ and I don't know if this is possible like so:

class a 
{

public:
a (int x);
a (int x, int b, char g);

};

a :: a(int x) : this(x, 6, 'h')
{

}
2
  • Does your compiler support C++11 features? Commented Sep 18, 2012 at 20:51
  • Look at the second answer in the question I linked to if you're on C++11 Commented Sep 18, 2012 at 20:53

2 Answers 2

3

New C++11 standard supports this feature (called delegating constructors). Syntax is like:

a::a(int x) : a(x, 6, 'h') {}

If your compiler doesn't support new standard, you will need to extract common behavior into another initialization method and call that method in the constructor body.

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

4 Comments

Thx, since i'm currently not using c++11 do i have no way of doing this ??
I have edited the answer: unfortunately not.
@DavidLimkys What is stopping you from using C++11 features? Is it because your compiler does not support it?
Ok thx for the quick answer :D @Mihai Todor Yes i am currently using mvs 2010.
0

It's possible in C++11, but not in earlier versions.

Generally, you can try putting common stuff into a (non-virtual) member function, and call that from your constructors. While this won't allow you to init everything (only stuff that you do in the constructor bodies, not initialization in the preambles), it might still be "better than nothing".

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.