Messages Order

  • + 0 comments

    I think my approach is quite similar to the others already published here. It involves the usage of a static variable.

    • I added a static variable "order", class-wise.
    • In addition, each instance of Message also contains its own copy of order, called order_.
    • On creation time, Message() calls set_order() which increments the global order by one, then copies that value to the interval variable order_. For that, the Message's constructor calls set_order().
    • Messages are sorted by order_.
    class Message {
    public: 
        Message() {
            // this will set the order or arrival, on creation time
            set_order();
        }
        Message(const string text): Message() {text_=text;}
        const string& get_text() {
            return text_;
        }
        
        // global variable to keep count of the number of messages created
        static int order;
        // public getter function
        int get_order() const { return order_; }
        // comparison operator
        bool operator<(const Message& other) const {
            return order_ < other.get_order();
        }
    private:
        string text_;
        
        // this is for internal use
        int order_;
        // this is called on creation time: set the order of arrival for the message
        void set_order() { order_ = ++Message::order; }
    };
    int Message::order = 0;
    
    class MessageFactory {
    public:
        MessageFactory() {}
        Message create_message(const string& text) {
            return Message(text);
        }
    };