I decided to start an extremely simple experiment to revise on things I already know, but came across two things that puzzled me. I have a class named Number, which only holds an integer named "value":
Code:
class Number
{
public:
Number(const int vl=0);
void set_value(const int value);
int get_value() const;
Number operator+(const Number &n) const;
Number operator-(const Number &n) const;
Number operator-() const;
Number &operator++();
Number operator++(int);
Number &operator=(const int n);
private:
int value;
};
ostream &operator<<(ostream &sout, const Number &n);
istream &operator>>(istream &sin, Number &n);
There is this thing that I can't understand. If I don't implement Number &operator=(const int n);, here is what happens:
Code:
Number n = 123; //constructor is called... I didn't know it would, but it makes sense
Number j=n; //Default copy constructor
j=n; //What??? The constructor is called!!!
I know I can forbid lines 1 & 3 by using the keyword explicit before the constructor's prototype, but that's not my point at all. I want to know why would a constructor be called twice for the same instance. I'd think this would be a syntax error. What does the standard say about this?
Here is the code for the constructor:
Code:
Number::Number(const int vl)
{
value = vl;
cout << "Constructor!" << endl; //to know when the constructor is called
}
Another issue: If I remove the keyword const from ostream &operator<<(ostream &sout, const Number &n), this is what happens:
Code:
cout << ++n << endl; //works ok
cout << n++ << endl; //syntax error!
cout << n << endl;
The error is: operators.cpp|41|error: no match for 'operator<<' in 'std::cout << (&n)->Number: operator++(0)'|
This applies for all functions that return Number instead of Number&, but I don't understand why. What if I didn't want n to be const? I can't think of a reason I'd want that right now, but I want to understand why things are working this way.
In case you are wondering, the reason I make trivial experiences like this is to understand the little details that I can't find in any book. This way I can understand how things really work, and prevent or fix potential bugs that will appear to me in the future.