By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
445,819 Members | 1,173 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 445,819 IT Pros & Developers. It's quick & easy.

How to explicitly allow object copy ?

P: n/a

Hi.

I would like to explicitly allow object copy, without writting a user
defined copy constructor.

I am looking for something like :

class C
{
public:
C(const C &c) { /* call compiler define copy constructor */ }
};

Is there any way to do that in C++ ?

Thank you for advance.

Oct 4 '06 #1
Share this Question
Share on Google+
3 Replies


P: n/a

Note that I would also find useful to do :

class C
{
public:
C(const C &c) { /* call compiler define copy constructor */ ; /* do
someting more */; }
};

Oct 4 '06 #2

P: n/a
fr***********@yahoo.fr wrote:
>
Hi.

I would like to explicitly allow object copy, without writting a user
defined copy constructor.

I am looking for something like :

class C
{
public:
C(const C &c) { /* call compiler define copy constructor */ }
};

Is there any way to do that in C++ ?
Yes:

class C {
public:
// C(const C &c);
// implicitly defined copy constructor is used.
};
};Note that I would also find useful to do :
>
class C
{
public:
* C(const C &c) { /* call compiler define copy constructor */ ;
* /* do someting more */; }
};
That won't fly.
Best

Kai-Uwe Bux
Oct 4 '06 #3

P: n/a

Kai-Uwe Bux wrote:
fr***********@yahoo.fr wrote:

};Note that I would also find useful to do :

class C
{
public:
C(const C &c) { /* call compiler define copy constructor */ ;
/* do someting more */; }
};

That won't fly.
Yes, derive from C.

class D : public C
{
public:
D( const D & d ) // will automatically copy the C parts for you
{
// do further stuff
}
};

except that you can't pass your C around as a C (even with a virtual
destructor), it would have to be as a D. If someone tries to clone
their C they'll slice.

You can also use a wrapper with aggregation thus:

class D
{
C c;

public:
D::D( const D & d )
: c( d.c ) // using default copy constructor
{
// anything else you want to do
}
};

Again though your users must use D.

The final solution is to implement copy-construction in terms of
default assignment, assuming you are not overloading that. (Usually
it's done the other way round and it's highly unlikely you'd want to
overload one without the other still here is the solution...)

C::C( const C & c )
{
*this = c;
// other stuff
}

C would have to be assignable, i.e. can't have const members or
references.
>

Best

Kai-Uwe Bux
Oct 4 '06 #4

This discussion thread is closed

Replies have been disabled for this discussion.