Re: Copy constructor ! by Robby
Robby
Fri Aug 19 15:18:01 CDT 2005
Hi, A little cofused may I add.....
What do you mean by:
No, if the initialiser list is empty, then every member will be
default-constructed if possible.
So then you're saying that the code fragment below would reconstruct the
member data (shallow copy):
#include <iostream>
using namespace std;
class SimpleCat
{
public:
SimpleCat();
SimpleCat(const SimpleCat &);
~SimpleCat();
int GetAge(int Decision);
void SetAge(int age, int Decision);
private:
int itsAge_Val;
int itsAge_Ref;
int itsAge_Pointer;
int itsAge_PHeap;
};
SimpleCat::SimpleCat()
{
cout << "Constructor called. \n";
itsAge_Val = 0;
itsAge_Ref = 0;
itsAge_Pointer = 0;
itsAge_PHeap = 0;
}
//Copy constructor with innitializer list empty!
SimpleCat::SimpleCat(const SimpleCat &rhs)
{
//this copy constructor does nothing.
cout << "\n *********Copy constructor does nothing*********\n";
}
SimpleCat::~SimpleCat()
{
cout << "Destructor called \n";
}
void SimpleCat::SetAge(int age,int Decision)
{
itsAge_Val = age;
}
int SimpleCat::GetAge(int Decision)
{
return itsAge_PHeap;
}
void Function0(SimpleCat theCat); //Passing an object by value
int main()
{
int a;
SimpleCat Frisky; //Declare for passing by value
Function0(Frisky); //Call by value a copy of the object
cout << "\nActual value set from constructor: " << Frisky.GetAge(1) <<
"\n";
cin >> a;
}
void Function0(SimpleCat theCat) //Passing by value
{
theCat.SetAge(10,1);
cout << "\nThe value of age in Function0 is: " << theCat.GetAge(1) <<
"\n";
}
What I am trying to understand is if I run the above program, will a member
wise copy be done. REMEMBER I am not talking about a deep copy where used
when members are pointers! I am simply talking about a shallow copy.
So then basically, if we know that a member-wise copy (Or shallow copy) is
made by the default copy constructor when passing an object to a function by
value, THEN if we provide our own copy constructor (with no code in it!) as
shown in the above code fragment, would the default copy constructor be smart
enough create a member shallow copy anyways?
--
Best regards
Robert
--
Best regards
Robert
"Victor Bazarov" wrote:
> Robby wrote:
> > The default copy constructor simply copies each member variable from the
> > object passed as a parameter to the member variables of the new object.
>
> The default copy constructor _copy-constructs_ each member. If that what
> you meant by "copies", then yes.
>
> > This
> > is called member -wise (or shallow copy). However if I provide my own copy
> > constructor but with no code in it, will a shallow copy still be made?
>
> No, if the initialiser list is empty, then every member will be
> default-constructed if possible.
>
> V
>