2

I want to assign a class a value on declaration so I made this basic class:

class   A
{
public:
    A   &operator=(int)
    {
        return (*this);
    }
};

and compiled it with this main:

int main(void)
{
    A x = 1;
}

but the compiler complained with this error message:

no viable conversion from 'int' to 'A'

    A x = 1;
      ^   ~

but when I compile with this main:

int main(void)
{
    A x;

    x = 1;
}

everything compiles smoothly


why does my first main not compile and how can I change the class A so that it compiles?

songyuanyao
  • 169,198
  • 16
  • 310
  • 405
Theo Walton
  • 1,085
  • 9
  • 24
  • 1
    Not exactly the case in your question, but will probably shed some light on it for you https://stackoverflow.com/questions/11706040/whats-the-difference-between-assignment-operator-and-copy-constructor – StoryTeller - Unslander Monica Jan 18 '18 at 06:31

1 Answers1

7

A x = 1; is initialization, not assignment; they're different things. It doesn't invoke assignment operator but requires converting constructor.

class   A
{
public:
    // converting constructor
    A (int) {} 

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

then

A x = 1; // initialize x via converting constructor
x = 2;   // assign x via assignment operator
songyuanyao
  • 169,198
  • 16
  • 310
  • 405