1

I overloaded the operator "=" to do something, but instead it goes and uses the constructor

class Date
{public:
    int x;
public:
    Date(int v1)
    {
        x = v1+1;
    }
    Date& operator=(Date& d)
    {
        x = x - 1;
    }
public:
    ~Date() {};
};

int main()
{
    Date d = 1;
    cout << d.x;
    //delete d;
    return 0;
}

I was expecting to print 0 but instead it prints 2(uses the constructor). Why is that? Also why won't it let me delete d? it says it must be a pointer to a complete object type.

  • It's because `Date d = 1;` expression calls the constructor. and `d = 1;` will call the assignment operator. – vahancho Jun 18 '19 at 09:19
  • 2
    As per your second question, you cannot `delete` what was not allocated with `new`. You should get [a good C++ book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) and learn the basics from it. – Yksisarvinen Jun 18 '19 at 09:20
  • `Also why won't it let me delete d` because you didn't new it. Don't try and learn C++ without a good book – UKMonkey Jun 18 '19 at 09:20
  • @Yksisarvinen get out of my head >. – UKMonkey Jun 18 '19 at 09:21
  • I'm not sure why you expected `Date d = 1` to invoke an `operator=` that takes a parameter of type `Date&`. Even `d = 1` on its own after the declaration won't work because the types don't match. – Blaze Jun 18 '19 at 09:24

1 Answers1

6

It should get priority, because this

Date d = 1;

Is not assignment, it's an object declaration with initialization. Initialization of class objects in C++ is the domain of constructors. Don't let the syntax (using = 1 as an initializer) confuse you.

To get the assignment operator called, the left hand side must be an existing object whose initialization already happened. Assignment only applies to preexisting objects. So if you add a statement like this:

d = 1;

It could call the assignment operator as you expect (after some other errors are fixed).

Also why won't it let me delete d? it says it must be a pointer to a complete object type.

The error seems pretty self explanatory to me. You can only call delete on a pointer operand. And the pointer must be pointing at an object previously create with new.

StoryTeller - Unslander Monica
  • 165,132
  • 21
  • 377
  • 458
  • 1
    And `operator=` forgot to `return *this;` – Nikos C. Jun 18 '19 at 09:24
  • Thank you all, you were of great help! I'm new to C++ and i'm trying my best to understand –  Jun 18 '19 at 09:36
  • @Theodor3699 - The best way to understand is to get [a good book from our curated list](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) and work through it. The C++ community here vets those books. – StoryTeller - Unslander Monica Jun 18 '19 at 09:37
  • `d = 1` actually, in this case, constructs an object from the `int`, and then calls the assignment operator to assign it to `d` (before any elision occurs of temporaries). – Peter Jun 18 '19 at 09:40