Which constructor is used during copying of a class?

If I have a vector of classes, like this:

std::vector<MyClass> vec;

How do I know what constructor the compiler will use to copy the individual class instances when I then do something like this:

std::vector<MyClass> newvec(vec); // what just happened?
You look at the documentation or the implementation.
Or you could put breakpoints in the likely candidates, run it and see what happens.

It's actually quite beneficial to have a set of classes, fully decked out with each type of constructor and operator. Put cout statements in each method and then try creating vectors of them (for e.g.) and see what methods are actually called when. You'll be surprised.

Jim
If you defined your own copy constructor, it will use that. If not then the compiler implicitly generates a default one for you.

This is OK, provided that there are no member variables that are references or const, in which case you should write your own.

Good Luck ! :)
So If I have some methods like this:

1
2
3
MyClass();
MyClass(MyClass&);
MyClass const& operator=(Myclass const&);


Which will it use? And how do you know? My guess is the 2nd one but I don't know how to find out from the vector documentation alone.. I don't really want to just test it because I'd like to know why it's like that and where I can find the documentation that says it.
Last edited on
Neither member function will be called.

For object newvec of type std::vector<MyClass> will be called copy constructor

vector( const vector &vec )

So this constructor can call only const function for the vector specified as an argument. However class MyClass has no the copy constructor that accepts const reference to MyClass.

I think you will get a compilation error.
I was going to say some thing but vlad covered it better.
Last edited on
Ok that makes sense. Thanks.
Topic archived. No new replies allowed.