0
0
C++programming~5 mins

Object interaction in C++

Choose your learning style9 modes available
Introduction

Objects often need to work together to solve problems. Object interaction lets them share information and actions.

When one object needs to ask another object for information.
When objects need to work together to complete a task.
When you want to organize your program into smaller parts that communicate.
When modeling real-world things that affect each other.
Syntax
C++
class ClassName {
public:
    ReturnType methodName(Parameters) {
        // code
    }
};

// Using objects to call methods
object1.methodName(args);

Objects call each other's methods to interact.

Methods can return values or change object states.

Examples
A Switch object interacts with a Light object by calling its method.
C++
class Light {
public:
    void turnOn() {
        // turn light on
    }
};

class Switch {
public:
    void press(Light &light) {
        light.turnOn();
    }
};
One Person object greets another Person object.
C++
class Person {
public:
    void greet(Person &other) {
        std::cout << "Hello!" << std::endl;
    }
};
Sample Program

The Owner object calls the Dog object's bark method by passing the Dog object to its own method.

C++
#include <iostream>

class Dog {
public:
    void bark() {
        std::cout << "Woof!" << std::endl;
    }
};

class Owner {
public:
    void callDog(Dog &dog) {
        std::cout << "Come here, dog!" << std::endl;
        dog.bark();
    }
};

int main() {
    Dog myDog;
    Owner me;
    me.callDog(myDog);
    return 0;
}
OutputSuccess
Important Notes

Objects interact by calling each other's methods, often passing themselves or other objects as arguments.

Use references or pointers to avoid copying objects when interacting.

Keep interactions simple to make your code easier to understand.

Summary

Objects communicate by calling methods on each other.

Passing objects as arguments lets one object affect another.

Object interaction models real-world relationships in code.