Is it bad design to pass the containing object as an argument to a method of a contained object, like in the simplified example below?
class A
{
private B _containedObject;
public A(B b)
{
_containedObject = b;
//...
}
public void SomeMethod()
{
//...
_containedObject.SomeMethod(this);
//...
}
}
class B
{
public void SomeMethod(A a)
{
//do something with a
}
}
P.s. The above example is simplified to illustrate merely the containment relation and passing the containing object to the contained object, and does not in itself illustrate the purpose of doing so. Rest assured though that there is a purpose.
There are times when you might want to pass the containing object as a parameter to a contained object. As other posters have noted, it is called “double dispatch”. The Smalltalk language provides a classic example.
The example is about adding together integers and floats (or other types of numbers). In C++ or Java, your integer class would have polymorphic methods like:
Each add method could implement the different kinds of addition correct. The compiler uses the type information to select the right method. The statement Integer(6).add(Float(1.0)) would invoke the Integer::add(Float) method.
Smalltalk, unlike C++ and Java, is dynamically typed. A Smalltalk class can only have one method named add.
Integer::add(Object)
The compiler does not know the class of “object”. For that reason, Smalltalk cannot implement the add the same way as C++ or Java. Instead, Smalltalk uses double dispatch. It works like this:
The other number classes like Float, Fraction and even Integer implement the method addToInteger().
Double dispatch solves the problem of how to implement man operations polymorphically in a dynamically typed language. But there is a more common use: the visitor pattern. I’ll put that in a separate answer.