Jump to content

C++ inheritance problem


Recommended Posts

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 ?

Link to comment
Share on other sites


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.

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
  • Recently Browsing   0 members

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