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"?
CodePudding user response:
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.
CodePudding user response:
As suggested by @HolyBlackCat
This will work as expected.
#include <iostream>
class UnusualClass{
public:
UnusualClass(const int &n){
std::cout<<"Copy initialization";
}
explicit UnusualClass(const int &&n){
std::cout<<"Direct initialization";
}
};
int main ()
{
UnusualClass k1(5);
UnusualClass k2 = 5;
return 0;
}