C++ ques doubt 2 and 3

Hi,

I had an exam on
Last edited on
You could have asked these in your other thread.

2. Think about this a bit. In some cases, a copy constructor/assignment operator won't be needed (the defaults are sufficient), but there are other things to consider. What if the class contained a pointer?

3. Sounds like they just want a description of what occurs here. A lot will be missing, but the point is for you to recognize the constructor that Y is using.
3. read about explicit keyword.
The copy constructor will be called in this with no problems. But if you do this:
Y y = func(x); //illegal, as the constructor is explicit

had the code been like this:

1
2
3
4
class X { … }; class Y { public: Y(const X& x); … }; 
Y func(Y y) { … }
X x;
Y y = func(x); //perfect, implicit conversion 
So is "Y(const X& x);" making a copy constructor??
After going through the concepts below is my understanding...

Y func(Y y) { … }
- Compiler will call the default constructor of class Y if its not defined during compilation of this step.

X x;
- Compiler creates object for class X.

Y y = func(Y(x));
- Compiler calls and executes the definition of "explicit Y(const X& x);" and creates a copy constructor.

Please clarify...
A copy constructor is like this.

explicit Y(const Y& x);

explicit means that you have to tell explicitly how are you going to create an object, it is not going to do anything implicitly. So you are correct. But it is not a copy constructor, it is a user defined constructor.

Topic archived. No new replies allowed.