The default copy constructor does member wise copy (thanks to Yuri whose comment below clarified this, as I had originally said bitwise copy). You can see this more clearly by changing your constructor and by providing an output operator for Object:
#include <algorithm> // for fill()
using namespace std;
class Object {
private:
int arr[10];
public:
Object(int i=0);
friend ostream& operator<<(ostream& ostr, const Object& obj);
};
Object::Object(int i)
{
fill(arr, arr + 10, i);
}
ostream& operator<<(ostream& ostr, const Object& obj)
{
ostr << "outputting member 'int arr[10]' of size " << sizeof(obj.arr)/sizeof(int) << "\n";
for (int i = 0; i < sizeof(obj.arr)/sizeof(int); i++) {
ostr << obj.arr[i] << ", ";
}
ostr << "\n";
return ostr;
}
void test(Object &first, Object other)
{
cout << "Test" << endl;
cout << first << endl;
cout << other << endl;
return;
}
int main(int argc, char** argv)
{
Object x(4);
Object y(x);
test(x, y);
return 0;
}
"What then is the case when instead of declaring int arr[10], a int *arr is used and the arr is dynamically allocated in the constructor, using the new keyword?"
In that case both objects will point to the same address, which means y could change the dynamically allocated array of x, and vice versa. Probably not what you want. So you would need to supply a copy constructor to avoid this:
#include <algorithm> // for fill()
using namespace std;
class Object {
private:
int *p;
public:
Object(int i=0);
Object(const Object& rhs);
~Object();
friend ostream& operator<<(ostream& ostr, const Object& obj);
};
Object::Object(int i)
{
p = new int[10];
fill(p, p + 10, i);
}
Object::Object(const Object& rhs)
{
p = new int[10];
for(int i = 0; i < 10; i++) {
p[i] = rhs.p[i];
}
}
Object::~Object()
{
delete [] p;
}
ostream& operator<<(ostream& ostr, const Object& obj)
{
for (int i = 0; i < 10; i++) {
ostr << obj.p[i] << ", ";
}
ostr << "\n";
return ostr;
}
void test(Object &first, Object other)
{
cout << "Test" << endl;
cout << first << endl;
cout << other << endl;
return;
}
int main(int argc, char** argv)
{
Object x(4);
cout << x << endl;
Object y(5);
test(x, y);
return 0;
}