Calling constructor explicitly in copy constructor

Hi, I do know this can be done with the destructor (X::~();), but it does not seems to work with the constructor.

I do not want to repeat the code of the constructor again, so I'd like to know if it is possible to call the constructor this way.

I know it seems contradictory because constructors are called when you are creating a new object, and not after the object has been created.


1
2
3
4
5
6
ColeccionCoches::ColeccionCoches(const ColeccionCoches &origen) {
	
this(origen.NumCoches);

//.... more code here irrelevant to the question
}


Last edited on
This is what initializer lists are for. Consider this:
1
2
3
4
5
6
7
8
class X
{
  int x;
public:
  X() : x(0) {} //initializes x to 0
  X(const int& x) : x(x) {} //initializes this->x to the parameter x
  X(const X& from) : x(from.x) {} //initializes x to the x in the other X object
};

You can separate multiple constructor calls with a comma , and you can still put code in the braces {} which will be executed after the initializer lists calls the constructors.
Last edited on
This currently only works for members. C++0x supports delegating constructors, but until now this usually has been done with some sort of init function.
Topic archived. No new replies allowed.