TIP: Click on subject to list as thread! ANSI
echo: c_plusplus
to: PAUL DRUGGITT
from: VADIM DAVYDOFF
date: 1997-05-25 05:50:00
subject: passing structures to functions

Hello Paul!
16 May 97 22:57, Paul Druggitt wrote to All:
 PD>  Now, is it possible to write a single function that will accept ANY
 PD>  structure as a parameter, stating which member to compare?
According to the EchoTag, we are talking about C++, right?
Simply use a base class with the only data member as a type identifier.
class CBase
  {
  public:
    int m_iType;
  };
Then, derive all your other classes from it just like:
class CBig1 : public CBase
  {
  public:
    CBig1 () {m_iType = 1;}
    char m_acData1 [20];
    char m_acData2 [100];
  };
class CBig2 : public CBase
  {
  public:
    CBig2 () {m_iType = 2;}
    char m_acData1 [25];
    char m_acData2 [200];
    int m_aiData [10];
  };
Use a pointer to the CBase as your function paramter. In function body check 
the type member and then convert a CBase* to the appropriate type.
void f (CBase* p)
  {
  switch (p->m_iType)
    {
    case 1:
      // use (CBig1 *)p as you need
      break;
    case 2:
      // use (CBig2 *)p as you need
      break;
    // ...
    }
  }
This is a simple but stupid way. Using virtual functions is a better, I hope 
you are familiar enough with C++.
Vadim
--- GoldED 2.41+
---------------
* Origin: ---- * BackSpace * St.Petersburg * Russia * ---- (2:5030/122.72)

SOURCE: echomail via exec-pc

Email questions or comments to sysop@ipingthereforeiam.com
All parts of this website painstakingly hand-crafted in the U.S.A.!
IPTIA BBS/MUD/Terminal/Game Server List, © 2025 IPTIA Consulting™.