Archived

This topic is now archived and is closed to further replies.

Eber Kain

copy constructor

Recommended Posts

MadKeithV    992

  
class ExampleClass
{
int m_someMember;
public:
ExampleClass() : m_someMember(0) {} // Ordinary constructor

ExampleClass( const ExampleClass &c ) : m_someMember( c.m_someMember) {} // Copy constructor

};


Basically, the copy constructor always follows the syntax Classname( const Classname &otherObject), and allows you to "copy" the values of otherObject into the object under construction.

Share this post


Link to post
Share on other sites
Alimonster    185
A copy constructor is invoked when you want to create an object based on another of the same type. For example:


  class SomeObj
{
private:
int x;
public:
SomeObj(const SomeObj& copyFromMe): x(copyFromMe.x)
{
}
};


A copy constructor simply uses the same syntax as a normal constructor except that it has one object of the same type.

It would be invoked when passing a class by value or when you create a new object:

SomeObj first;
SomeObj second(first); // copy constructor here

Share this post


Link to post
Share on other sites
Eber Kain    130
I need it for using STL list, it reccomends using an overloaded = operator at the same time.

I guess you could make the = operator do all the member transfers, and just the assignment operator in the constructor.

Share this post


Link to post
Share on other sites
Kitt3n    468
You only need a copy-constructor if you are doing something
fancy with memory allocation - if you aren''t don''t bother
because the compiler will generate a default copy constructor

following example where we are doing fancy memory stuff:

class A
{
char* data;

A () { data = new char[10]; }
~A() { if (data) delete data; }
};

Following situation:

A instance1;
A instance2 (instance1);

In this case the default copy-constructor would copy the
pointer (not the data pointer to!) which means that when
the objects get destroyed in the destructor, you are in for trouble...
Instance1 will free the data-block... instance 2 will
try to free the same data-block - not good...

In this case you want a copy-constructor which allocates
enough memory to hold the data and memcpy the data into
the new instance

Oh and if you use operator= be carefull for instance1=instance2, check this with the operator=param and just return if they are
the same

Regards
/Roger

Share this post


Link to post
Share on other sites