Home > Software design >  Problem in passing object to an function in main
Problem in passing object to an function in main

Time:09-17

How to pass object in main function. I want to show back to back send and received message by user1 to user 2 and user2 to user1, but when i calling a function using caller object it only shows user1 send msg

Please help me out to this. I am not understand what i do, can i make a separate copy of object of pass reference in sendMsg() function in Inbox class

#include<bits/stdc  .h>

using namespace std;

class Message{
private:
  list<string> msg;
public:
  void setMsg(string s){
    this->msg.push_front(s);
  }

  list<string> getMsg(){
    return this->msg;
  }

  void showMsg(){
    for (auto it = this->msg.begin(); this->msg.begin() != this->msg.end(); it  )
      cout << *it << endl;
  }
};

class Inbox{
private:
  Message m;
  list<string> r_msg;

public:
  void sendMsg(Inbox &i, string s){
    this->m.setMsg(s);
    i.r_msg.push_front(s);
  }

  void showSendMsg(){
    m.showMsg();
  }

  void showRecievedMsg(){
    for (auto it = this->r_msg.begin(); this->r_msg.begin() != this->r_msg.end(); it  )
            cout << *it << endl;
  }
};

int main(){
  Inbox user1, user2;
  user1.sendMsg(user2, "hello");
  user1.showSendMsg();
  user2.sendMsg(user1, "Hi");
  user2.showRecievedMsg();

  user1.sendMsg(user2, "What are you doing?");
  user1.showSendMsg();
  user2.sendMsg(user1, "Nothing!!");
  user2.showRecievedMsg();

  user1.sendMsg(user2, "Are you there?");
  user1.showSendMsg();
  user2.sendMsg(user1, "I am lil bit buzy");
  user2.showRecievedMsg();
  return 0;
}

CodePudding user response:

The problem is that in line 18 you're comparing this->msg.begin() to the end, instead of the actual position with the iterator.

Line 18: for (auto it = this->msg.begin(); this->msg.begin() != this->msg.end(); it )

Should be

for (auto it = this->msg.begin(); it != this->msg.end(); it )

The error you're getting is because you're comparing the same thing over and over, the loop will keep iterating (increasing the iterator), and it tried do dereference the invalid iterator.

You made the same mistake in line 39.

  • Related