1

Got stuck here while going through Bruce Eckel TIC++

Create a class with an assignment operator that has a second argument, a string that has a default value that says “op= call.” Create a function that assigns an object of your class to another one and show that your assignment operator is called correctly.

Is this really possible. Does C++ allow operator=() to have multiple argument?? I tried this:

class X
{
public:
    X& operator=(const X& x, string val = "op=call")  //! error
    {
        // ...
    }
};

int main()
{
    X x1;
    X x2;
    x2 = x1;
}

Error given by compiler:

[Error] 'X& X::operator=(const X&, std::string)' must take exactly one argument

I think this is not a valid question or if it is then how to provide multiple argument to assignment operator??

Azeem
  • 11,148
  • 4
  • 27
  • 40
abhi_awake
  • 186
  • 1
  • 8
  • That doesn't look legal to me. And what's the point of `val`? Why would checking for equality require a third argument? And how would that argument even be given, unless it entirely relies on default behavior? – Carcigenicate Jun 27 '17 at 15:34
  • 3
    [I would find a different book](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) – NathanOliver Jun 27 '17 at 15:36
  • Correct. There's no point in adding third argument. Even if we try so, compiler comes up with strict error.. **Exactly one arg** – abhi_awake Jun 27 '17 at 15:37
  • The operator should be a free function, not a member of the class – balki Jun 27 '17 at 17:18
  • 2
    @balki `operator=` can't be a free function. It must be implemented as a member function, taking exactly one argument. – Igor Tandetnik Jun 27 '17 at 18:54
  • @NathanOliver Correct idea, but bad link: it's recommending exactly this book in 5th place! – Walter Jun 27 '17 at 22:50
  • @NathanOliver I have edited said link and removed this book to the "classics/older" section ... – Walter Jun 27 '17 at 23:04

1 Answers1

1

The most recent edition of Thinking in C++, Vol 1 was published in 2001. New C++ Standards have been published three times since then (2003, 2011 and 2014).

My guess is that Eckel is demonstrating a loophole in the Standard, which was later corrected. (Or possibly, since this loophole I'm presupposing would be such an edge case, your compiler may have merely implemented the intended behavior accidentally, instead of a strictly following the Standard)

James Curran
  • 101,701
  • 37
  • 181
  • 258
  • Even C++98 specified that a copy assignment operator (or any overloaded assignment operator) have exactly one parameter. I suspect that your last sentence is correct - the book's example was relying an accident of some early compiler(s). – Michael Burr Jun 27 '17 at 22:58
  • Even VC++6 wil not compile the assignment operator with a second parameter. – Michael Burr Jun 27 '17 at 23:10