utab wrote:
Dear all,
So passing and returning a class object is the time when to include the
definition of the copy constructor into the class definition.
Passing by value and returning by value are two ways of invoking copy
construction for objects of class type. But just because the copy
constructor is used doesn't mean you need to define it yourself. If you
don't define it, the compiler will do it for you. The compiler
generated copy constructor will perform a memberwise copy of all data
members and will copy base class objects using their copy constructors.
Unless that is not sufficient for your needs, you do not need to define
the copy constructor, even if you do copy objects.
But if we
don't call by value or return by value, we do not need to use the
copy-constructor.
Not true.
std::string s1("text");
std::string s2(s1);
s2 is constructed using the copy constructor of the std::string class,
but nothing is passed or returned by value.
So depending on the above reasoning I can avoid call
by value and return by value for class objects, this bypasses the
problem or it seems to me like that.
What problem?
Could any one give me some simple examples when copy constructors are
indispensible tools in C++ class implementations?
You should write a copy constructor for any class where the compiler
generated copy constructor is not sufficient. Generally this means
classes that own resources, e.g. memory referred to by a bald pointer.
Google for the "rule of three" too. If you need to write your own copy
constructor, you probably need to write your own assignment operator
and destructor as well.
Notice that the decision whether to write your own copy constructor or
rely on the compiler generated one has *nothing* to do with whether you
think the code you're about to write will copy objects. Even if you
don't plan to copy any objects immediately, you should still write the
copy constructor (or disable copying - see below) if the compiler
generated copy constructor is not sufficient. Otherwise, one day you or
someone else will come along, write some new code that does copying and
unwittingly introduce bugs because the wrong copy constructor is used.
You have another option too. If you want to disable copying for your
class, declare the copy constructor private. Declare the assignment
operator private too because it certainly makes no sense to disable
copying but allow assignment.
class foo
{
private:
foo(const foo&);
foo& operator=(const foo&);
};
An attempt to copy or assign foo objects will result in a compile
error. Declaring your own copy constructor (even though it is private
and you have not provided a definition) suppresses the compiler
generated one.
Gavin Deane