Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objects that can be initialized but not assigned

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?

like image 298
Galaxian Avatar asked Feb 01 '17 08:02

Galaxian


People also ask

Why does copy constructor work for initialization but not for assignment?

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.

What is object initialization?

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.

What happens if you don t initialize a variable c++?

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.

What is object initialization in C++?

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.


2 Answers

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 
like image 152
Yousaf Avatar answered Sep 19 '22 05:09

Yousaf


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;

like image 31
Jonas Avatar answered Sep 22 '22 05:09

Jonas