Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I write different copyCtor for const and non-const instances?

I have the following problem:

I have a class which should do this:

Obj o;
Obj o1(o), o1=o; // deep-copies
const Obj c(o), c=o; // deep-copies
const Obj c1(c), c1=c; // shallow-copies
Obj o2(c), o2=c; // deep-copies

How can I do this preferably without inheritance? (I mean I would do Const_obj inheriting from Obj otherwise.)

EDIT:

Using o.clone() directly is not an option because then I could easily introduce bugs by accidentally not cloning.

EDIT:

Finally, there is a proper, complete solution with lazy evaluation using the idea from Effective C++ by Scott Meyers. Check out my answer below.

like image 223
Barney Szabolcs Avatar asked Nov 12 '12 12:11

Barney Szabolcs


1 Answers

No, you can't.

  • A constructor can not be cv-qualified, so you can't force it to construct a const object.
  • The return type of a function (including operators) is not a part of it's signature, so you can't overload a function with just changing it's return type.

Also, if it was possible, I would find it really confusing. Just make methods that suit your needs, and name them in an unambiguous way.

like image 72
SingerOfTheFall Avatar answered Sep 23 '22 05:09

SingerOfTheFall