开发者

Calling a chain of functions at different class inheritance levels

开发者 https://www.devze.com 2023-02-27 23:39 出处:网络
Given: class Foo { public: void Method1(); } class Bar extends Foo { public: Bar* Method2(); } class Baz extends Bar {

Given:

class Foo {
 public:
   void Method1();
}
class Bar extends Foo {
 public:
   Bar* Method2();
}
class Baz extends Bar {
 public:
   Baz* Method3();
}

So,

someObject *b = new Baz();
b->Method3()->Method2()->Method1();

This will work, as Baz() contains all methods including Method2(), Bar contains Method1();

But, due to return type开发者_开发知识库 this seems to be a bad idea - when accessing simpler Method1() at first inheritance level before calling more complex Method3(), and having to keep this calls in single line..

b->Method1()->Method2()->Method(3); // will not work?

Also, someone told me that putting try.. catch.. throw inside one of those Method's will occasionally exit the chain without calling next method at wrong value. Is this true?

So how to properly implement method chaining in C++?


That's what virtual methods are for. From the syntax errors I gather that you are new to C++

struct Base
{
    virtual Base* One() { return this; };
    void TemplateMethod() { this->One(); }
};

struct Derived : public Base
{
    virtual Base* One() { /* do something */ return Base::One(); }
};

When you call TemplateMethod:

int main() 
{ 

      Base* d = new Derived();
      d->TemplateMethod(); // *will* call Derived::One() because it's virtual

      delete d;

      return 0;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号