How exactly do “Objects communicate with each other by passing messages”?

前端 未结 10 560
无人及你
无人及你 2021-01-30 17:34

In several introductory texts on Object-oriented programming, I\'ve come across the above statement.

From wikipedia, \"In OOP, each object is capable of receivi

10条回答
  •  甜味超标
    2021-01-30 18:19

    In OOP, objects don't necessarily communicate with each other by passing messages. They communicate with each other in some way that allows them to specify what they want done, but leaves the implementation of that behavior to the receiving object. Passing a message is one way of achieving that separation of the interface from the implementation. Another way is to call a (virtual) method in the receiving object.

    As to which of your member function calls would really fit those requirements, it's a bit difficult to say on a language-agnostic basis. Just for example, in Java member functions are virtual by default, so your calls to a.methodA() and b.methodB() would be equivalent to passing a message. Your (attempts a) calls to b.methodA() and a.methodB() wouldn't compile because Java is statically typed.

    On the contrary, in C++, member functions are not virtual by default, so none of your calls is equivalent to message passing. To get something equivalent, you'd need to explicitly declare at least one of the member functions as virtual:

    class A { 
        virtual void methodA() {}
    };
    

    As it stands, however, this is basically a "distinction without a difference." To get some idea of what this means, you need to use some inheritance:

    struct base { 
        void methodA() { std::cout << "base::methodA\n"; }
        virtual void methodB() { std::cout << "base::methodB\n"; }
    };
    
    struct derived { 
        void methodA() { std::cout << "derived::methodA\n"; }
        virtual void methodB() { std::cout << "derived::methodB"; }
    };
    
    int main() { 
        base1 *b1 = new base;
        base2 *b2 = new derived;
    
        b1->methodA();   // "base::methodA"
        b1->methodB();   // "base::methodB"
        b2->methodA();   // "base::methodA"
        b2->methodB();   // "derived::methodB"
        return 0;
    }
    

提交回复
热议问题