mercredi 27 janvier 2016

Return type of << operator overloading function in C++

I have create a program to overload << operator for my class. I have a doubt about the return type of the overloaded method.

When i am returning the out from the overloaded operator function the program is working fine.

But when i am not returning any thing from the function the program crashing under one condition.

In many C++ resource i have read that the return type is necessary to print operators in cascading .

Condition 1 : Passing When i am using statement

// cout<<"\n"<<mv1<<mv2<<mv3; Every thing is working fine. Passing without return from overloaded function.

Condition 2:Failing When i am using statemtent cout<<"\n"<

This i know that return was not there so the program crashed at runtime.

But the question is what made program run in Condition 1 . Even without the return statement was not present in the overloading function.

Program below

I have create a program to overload << operator for my class.

I have a doubt about the return type of the overloaded method.

When i am returning the out from the overloaded operator function the program is working fine.

But when i am not returning any thing from the function the program crashing under one condition.

In many C++ resource i have read that the return type is necessary to print operators in cascading .

Condition 1 : Passing When i am using statement

// cout<<"\n"<<mv1<<mv2<<mv3; Every thing is working fine. Passing without return from overloaded function.

Condition 2:Failing When i am using statemtent cout<<"\n"<

This i know that return was not there so the program crashed at runtime.

But the question is what made program run in Condition 1 . Even without the return statement was not present in the overloading function.

Program below

#include <iostream>
#include <stdio.h>

using namespace std;

class myvar{

  private:
  int var_x,var_y;

  public:

  friend ostream& operator<<(ostream &out,myvar n);
  void setvalue(int x,int y)
  {
     var_x = x ;
     var_y = y ;
  }

};

ostream& operator<<(ostream &out,myvar n)
{
cout<<"("<<n.var_x<<","<<n.var_y<<")"; 
//return out;

}


int main()
{
 myvar mv1,mv2,mv3;
 mv1.setvalue(10,20);
 mv2.setvalue(30,40);
 mv3.setvalue(50,60);

//Working

    // cout<<"\n"<<mv1<<mv2<<mv3;

//Not Working

    // cout<<"\n"<<mv1<<mv2<<mv3<<"Hello"<<1243<<11.5;

}

Aucun commentaire:

Enregistrer un commentaire