0

Test code:

    Date mydate{31,12,1976};
    cout <<mydate.set(1,1,1978)<< mydate << "\n";
    cout <<mydate;

output:

1-1-1978 31-12-1976

1-1-1978

opeator<< declaration for my class:

    friend std::ostream& operator<<(std::ostream& os,  Date date);

operator<< definition for my class:

    std::ostream& operator<<(std::ostream& os,  Date date)
    {
        return os << date.m_month_day <<" "<< date.m_month <<" "<< date.y_year<<" ";
    }

I am using extractor operator function for my class. But i can't output in the same line when object changed. As you can see. What should i do?

  • 1
    Please make a [mre]. In particular, the definition of `Date::set`. Also, before c++17, the order of evaluation of arguments to `cout` is unspecified. – cigien Sep 09 '20 at 12:24
  • I don't see anything strange? Two values are printed on one line, then an explicit newline, then a new value? What did you expect to get? – Panagiotis Kanavos Sep 09 '20 at 12:24

1 Answers1

4

You are making the assumption that in

cout << A << B;

that A must be evaluated before B. That is not true.

Of course the value of A must be output before the value of B, but that could happen even though B is evaluated before A. That is clearly what is happening in your case.

The simplest answer would be to upgrade to C++17. In C++17 the rules were changed so that (using the example above) A must be evaluated before B. If you're not able to upgrade to C++17 there's nothing you can do except change your code.

john
  • 85,011
  • 4
  • 57
  • 81