Messages Order

  • + 16 comments

    Here are the things you need to do to solve this.

    1. Implement empty constructor method and constructor method with the text for Message class
    2. Implement get_text() method for Message which will return the string variable of the Message object
    3. Implement create_message() method for MessageFactory class by creating new Message object with given text and returning it
    4. In order for fix_order() method to be able to sort Message objects, each Message object needs to have an id variable which is distinct for each object. Think of it like a serial number for each of the Message objects which we will use to sort them. So create an appropriate id variable in the Message class.
    5. Then overload the < operator in Message class which should compare the id of two Message objects and return true or false accordingly if the first id is smaller or greater than the second id.

    Below is my complete solution.

    class Message {
    private:
        string text;
        static int id;
        int current_id;
    public:
        Message() { current_id = ++id; }
        Message(string t){ current_id = ++id; text=t; }
        const string& get_text() {
            return text;
        }
        // overloaded < operator
        bool operator < (const Message& M2) {
            if(current_id < M2.current_id)
                return true;
            else
                return false;
        }
    };
    int Message::id = 0;
    
    class MessageFactory {
    public:
        MessageFactory() {}
        Message create_message(const string& text) {
            Message m = Message(text);
            return m;
        }
    };