I need to create a class whose objects can be initialized but not assigned.
I thought maybe I could do this by not defining the assignment operator, but the compiler uses the constructor to do the assignment.
I need it to be this way:
Object a=1; // OK a=1; // Error
How can I do it?
2 Answers. Show activity on this post. The copy constructor is used to create a new object while the copy assignment operator is used to change an already existent object.
An object initializer is an expression that describes the initialization of an Object . Objects consist of properties, which are used to describe an object. The values of object properties can either contain primitive data types or other objects.
If you don't initialize an variable that's defined inside a function, the variable value remain undefined. That means the element takes on whatever value previously resided at that location in memory.
Dynamic initialization of object in C++ Dynamic initialization of object refers to initializing the objects at a run time i.e., the initial value of an object is provided during run time. It can be achieved by using constructors and by passing parameters to the constructors.
Making a
const will do the trick
const Object a=1; // OK
Now you won't be able to assign any value to a
as a
is declared as const
. Note that if you declare a
as const
, it is necessary to initialize a
at the time of declaration.
Once you have declared a
as const
and also initialized it, you won't be able to assign any other value to a
a=1; //error
You can delete the assignment operator:
#include <iostream> using namespace std; struct Object { Object(int) {} Object& operator=(int) = delete; }; int main() { Object a=1; // OK a=1; // Error }
Alternative Solution
You can use the explicit keyword:
#include <iostream> using namespace std; struct Object { explicit Object(int) {} }; int main() { Object a(1); // OK - Uses explicit constructor a=1; // Error }
Update
As mentioned by user2079303 in the comments:
It might be worth mentioning that the alternative solution does not prevent regular copy/move assignment like
a=Object(1)
This can be avoided by using: Object& operator=(const Object&) = delete;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With