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')
{

}
Community
  • 1
  • 1
David Limkys
  • 4,907
  • 5
  • 26
  • 38

2 Answers2

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.

Zdeslav Vojkovic
  • 14,391
  • 32
  • 45
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".

Christian Stieber
  • 9,954
  • 24
  • 23