I want to make chain-calling like jquery-way in c++. The sample:
$('#obj').getParent().remove();
So, as I understand, each method of the class should return the pointer to himself (this).
Everything is okay until I call base-derived methods. The code:
class Base
{
Base *base1() { return this; }
Base *base2() { return this; }
};
class Derived : Base
{
Derived *derived1() { return this; }
Derived *derived2() { return this; }
};
Derived *obj = new Derived();
obj->derived1()->derived2(); // Everything is okay
obj->derived1()->base1()->derived2(); // Fail at second step
Sure, the base1 returns the pointer for the Base. Are there any ways to make automatic casting?
UPD: Maybe that’s possible with macros? Like
#define CORRECT_RETURN (this)
and
Base::base1() {
return CORRECT_RETURN;
}
Something in this way. Or the compiler will not look at such construction?
Yes. Override the
base1andbase2methods inDerivedto change their return value fromBase*toDerived*, e.g.This is called covariance of return types and is legal in C++.
Assuming you want to actually use some functionality implemented in the base class methods without repeating it, you would do something like this:
Before you ask, no, you cannot create a situation where each derived class of the base automatically overrides the
base1andbase2methods using return types with the appropriate covariance. You have to do it manually every time, or else write a lot of scaffolding code to make it look like that’s what’s happening, which is usually more trouble than its worth.