The answer is No. The creation of the object memory is done via the new instruction. Copy constructor is then in charge of the actual copying (relevant only when it's not a shallow copy, obviously). You can, if you want, explicitly call a different constructor prior to the copy constructor execution.
The default constructor creates the exact copy or shallow copy of the existing object. Thus, the pointer p of both the objects point to the same memory location.
Copy Constructors is a type of constructor which is used to create a copy of an already existing object of a class type. It is usually of the form X (X&), where X is the class name. The compiler provides a default Copy Constructor to all the classes.
Do we have to explicitly define a default constructor when we define a copy constructor for a class?? Please give reasons.
eg:
class A
{
int i;
public:
A(A& a)
{
i = a.i; //Ok this is corrected....
}
A() { } //Is this required if we write the above copy constructor??
};
Also, if we define any other parameterized constructor for a class other than the copy constructor, do we also have to define the default constructor?? Consider the above code without the copy constructor and replace it with
A(int z)
{
z.i = 10;
}
Alrite....After seeing the answers I wrote the following program.
#include <iostream>
using namespace std;
class X
{
int i;
public:
//X();
X(int ii);
void print();
};
//X::X() { }
X::X(int ii)
{
i = ii;
}
void X::print()
{
cout<<"i = "<<i<<endl;
}
int main(void)
{
X x(10);
//X x1;
x.print();
//x1.print();
}
ANd this program seems to be working fine without the default constructor. Please explain why is this the case?? I am really confused with the concept.....
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With