Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Make difference between copy and direct initialization

Create an “UnusualClass” class in which direct and copy initialization produce different effects throughout. In particular, the attempt of direct or copy initialization should produce on the screen the print "Direct initialization" or "Copy initialization"

#include <iostream>
class UnusualClass{
   public:
   UnusualClass(const int &n){
       std::cout<<"Copy initialization";
   }
   UnusualClass &operator=(const int &n){
       std::cout<<"Direct initialization";
   }
};
int main ()
{
    UnusualClass k1(5); // Should print "Direct initialization"
    UnusualClass k2 = 5; // Should print "Copy initialization"
    return 0;
}

Why do I get copy initialization for both cases?

How to make UnusualClass k1(5); prints "Direct initialization" and UnusualClass k2 = 5; prints "Copy Initialization"?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

I believe it’s impossible in general, but if you only want to support the two ways of initialization you listed, there are hacky solutions.


You need two constructors, one explicit and the other non-explicit. As you were already told in comments, operator= won’t help you, since both lines perform initialization and not assignment.

However, if the there are no other differences between the two constructors, the code won’t compile.

You need to make the explicit constructor "better" than its non-explicit counterpart, so that it will be preferred if possible (i.e. for direct-initialization), so the other is used as a fallback.

Figuring out how exactly to make one constructor "better" than the other is left as an exercise to the reader. There are at least three approaches:

  • Using lvalue references vs rvalue references.
  • Using ....
  • Using a helper class with a constructor with an int parameter.
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading