Jump to content

Recommended Posts

Posted

I have the following code :

class C {
virtual void exec();
};

class A : public C {
void exec();
};

int main() {
A a1,a2;
a1.exec();
a2.exec();
}

Utilising the fact that both a1 and a2 share the same base class, can there be way to call all the exec() by a single function call ?


Posted

No, not without some extra administration. Each call of exec will have a different this pointer, so all calls have to be done. But you can write a linked list or something like that, to automate that:

class C {
  C(): m_pNext( m_pRoot )
  {
  m_pRoot = this;
  }
  virtual void exec();

  void exec_all()
  {
  for( C *pc = m_pRoot; pc; pc=pc->m_pNext )
  pc->exec();
  }

  C *m_pNext;
  static C *m_pRoot;
};

C *C::m_pRoot = 0;
 
class A : public C {
  void exec();
};
 
int main() {
  A a1,a2;
  a1.exec_all();
}

When the list is dynamic, you'll have to write a C destructor which skips the object from the list.

Please sign in to comment

You will be able to leave a comment after signing in



Sign In Now
  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...