JS starter JS starter - 3 months ago 18
C++ Question

How to overload operator= used in initializing a new object?

I'm new to C++ and I'm trying to understand how Class works. I made a simple example for myself when I encounter this problem. My class has one private property

and I'm trying to initialize it with an int this way:
Number one = Number::ONE;
but it doesn't work. However, when I do this it works fine:
Number one; one = Number::ONE
. I prefer the first option. Please help!

Here is my complete code:

class Number {

void print() const;

Number& operator=(int);
int num;

Number& Number::operator=(int n) {
num = n;
return *this;

int main(int argc, const char * argv[]) {

Number n = Number::ONE; // doesn't work :(

return 0;

Number::Number() {
num = 0;

void Number::print() const {
cout << num << endl;


In C++, when you write

Number one = Number::ONE;

the compiler will not use the assignment operator to initialize one. The operator= function is only invoked when you have an existing object that you want to reassign a new value. Instead, in this case, the compiler tries to invoke a conversion constructor, a constructor that takes in an object of the type on the right-hand side of the equality. Since you haven't defined a constructor like that, you're getting a compiler error.

One way to do this would be something like this:

class Number {
     Number(int value); // <-- Conversion constructor

Number::Number(int value) {
    num = value;

Now, the code you've given here will compile properly.

You may want to do some reading into copy constructors, assignment operators, conversion constructors, and conversion assignment operators, since they're one of the trickier parts of routine C++ and often trip up people transitioning from basic C++ to more intermediate-level language techniques.