copy constructor

Started by
3 comments, last by Eber Kain 21 years, 6 months ago
can someone show me what a copy constructor is? I cant find an example in the MSDN.
www.EberKain.comThere it is, Television, Look Listen Kneel Pray.
Advertisement

  class ExampleClass{int m_someMember;public:ExampleClass() : m_someMember(0) {}   // Ordinary constructorExampleClass( 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.
It's only funny 'till someone gets hurt.And then it's just hilarious.Unless it's you.
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 
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.
www.EberKain.comThere it is, Television, Look Listen Kneel Pray.
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

visit my website at www.kalmiya.com

This topic is closed to new replies.

Advertisement