Term-End Examination
June, 2020

Message passing is a communication mechanism used in various programming paradigms, such as object-oriented programming and concurrent programming, to allow objects or processes to exchange information and coordinate their actions. It involves sending messages between different entities to request actions or share data.

In object-oriented programming, message passing is central to how objects interact with each other. Objects communicate by sending messages to each other’s methods, which allows them to collaborate and achieve complex tasks.

Let’s demonstrate the utility of message passing with an example in C++:

#include <iostream>
#include <string>

class Messenger {
    virtual void sendMessage(const std::string& message) = 0;

class EmailMessenger : public Messenger {
    void sendMessage(const std::string& message) override {
        std::cout << "Sending email: " << message << std::endl;

class TextMessenger : public Messenger {
    void sendMessage(const std::string& message) override {
        std::cout << "Sending text message: " << message << std::endl;

class ChatApp {
    Messenger* messenger;

    ChatApp(Messenger* msgService) : messenger(msgService) {}

    void sendChatMessage(const std::string& message) {
        std::cout << "Sending chat message: " << message << std::endl;

int main() {
    EmailMessenger emailService;
    TextMessenger textService;

    ChatApp chatWithEmail(&emailService);
    ChatApp chatWithText(&textService);

    chatWithEmail.sendChatMessage("Hello via email!");
    chatWithText.sendChatMessage("Hi via text message!");

    return 0;

In this example, we have three classes:

Messenger: An abstract base class representing a generic messaging service. It defines a pure virtual function sendMessage().

EmailMessenger and TextMessenger: Concrete classes that implement the sendMessage() method for sending messages through email and text messages, respectively.

ChatApp: A class that simulates a chat application. It takes a Messenger object as a parameter in its constructor. The sendChatMessage() method sends a chat message and delegates the actual sending to the associated Messenger object.

In the main function, we create instances of EmailMessenger and TextMessenger, then create ChatApp instances associated with these messengers. By using message passing, the ChatApp instances can send messages through different messaging services without knowing the specifics of how messages are sent. This demonstrates the flexibility and decoupling achieved through message passing in object-oriented programming.

Leave a Reply 0

Your email address will not be published. Required fields are marked *