Overloading the Insertion (<<) Operator

I am trying to overload the insertion operator for a class called resident. Whenever I run this, res.m_name does not out put unless I add an endl after res.m_name. This function is a friend function of resident.

1
2
3
4
5
6
7
8
9
10
11
12
ostream& operator<<(ostream& os, const resident& res)
{
  
  os << res.m_name
     << (res.m_is_alive == true ? " is alive " : " is dead ")
     << "with hair color " << res.m_hairColor
     << " and is"
     << (res.m_is_murderer == true ? " " : " not ")
     << "the murderer." << endl;

  return os;
}

Last edited on
There must be something else going on with your code.
Make sure that the object is valid before cout-ing it with the insertion operator.

Good luck!
Your code looks good so far. Can you show how you're reading/storing the resident's name?
This is the code in the header file
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
const int NAMEMAX = 100;

class resident
{
  public:
    resident();
    void hair_color_change(const int hair);
    void kill_me();
    friend ostream& operator<<(ostream& os, const resident& res);
    void name();
  
  private:
    char m_name[NAMEMAX];
    bool m_is_alive;
    bool m_is_murderer;
    int m_hairColor;
    
  
};
Can you make m_name a string?
Topic archived. No new replies allowed.