-3

I have an object of class A.

class A[
{
   int x;
   string y;
   float z;
    ....
}

Then I have an int, called "integer". How can I redefine the = operator in order to do something like

int integer;
A obj = integer;

in order to obtain something equal to the constructor call with NOT all members:

A obj(integer,",0); 
Bibby2881
  • 1
  • 1
  • 2
    Provide your own `operator=(int)`. – iBug Jun 24 '21 at 17:23
  • 9
    `A obj = integer;` calls a constructor, never `operator=`. `A obj; a = integer;` would call `operator=`. – HolyBlackCat Jun 24 '21 at 17:23
  • @iBug how can I do it? this is the question – Bibby2881 Jun 24 '21 at 17:26
  • @HolyBlackCat I modified the question, x is not the only member of class. – Bibby2881 Jun 24 '21 at 17:26
  • @Bibby2881 It doesn't matter. `A obj = integer;` still calls constructor, not assignment operator. Of course, you can provide both for your class. – Yksisarvinen Jun 24 '21 at 17:32
  • The *specific* how-can-I question with the above "code" doesn't need an assignment operator overload; it needs a *conversion constructor* (and possibly a copy-constructor at least declared, even though the latter can/will be elided). – WhozCraig Jun 24 '21 at 17:33
  • `A(int x_) : x{x_} { }` will allow `A obj = integer;` but since `integer` has not been initialized, it's sort of a train wreck beforehand. – Eljay Jun 24 '21 at 17:40
  • @Yksisarvinen I get this error: no viable conversion from 'int' to 'A' – Bibby2881 Jun 24 '21 at 17:43
  • 1
    Until your question is updated to reflect *real* code that is producing the error you're stating, whatever you're getting is irrelevant. To accomplish what you *seem* to be asking [requires a conversion constructor](https://godbolt.org/z/8jsMP5KWd). If that is not sufficient for your needs, then we need to see a properly configured [mcve] . – WhozCraig Jun 24 '21 at 17:57

1 Answers1

0

This is a little naughty, but:

#include <iostream>

using std::cout;
using std::endl;

class A {
public:
    int x;

    A & operator=(int value) {
        x = value;
        return *this;
    }
};

int main(int, char **) {
    A obj;

    obj.x = 5;
    cout << "Initially: " << obj.x << endl;

    obj = 10;
    cout << "After: " << obj.x << endl;

}

When run:

g++ Foo.cpp -o Foo && Foo
Initially: 5
After: 10

Is this what you're trying to do? Note that this is very naughty. class A is NOT an integer, and assigning it to an int is going to confuse people. C++ lets you do things that you probably shouldn't do, and this is one of them.

Joseph Larson
  • 8,530
  • 1
  • 19
  • 36