Jump to content
  • Advertisement


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

Eber Kain

copy constructor

This topic is 5738 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts


class ExampleClass
int m_someMember;
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
A copy constructor is invoked when you want to create an object based on another of the same type. For example:

  class SomeObj
int x;
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
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
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


Share this post

Link to post
Share on other sites

  • Advertisement

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!