Dany
Dany

Reputation: 2174

How to pass the structure to a function in C++ defined in another class?

I have a class Con as this:-

class Con
{
 public:
  struct MachineList
  {
    BSTR AccountId;
    BSTR MachineId;
    BSTR Make;
    char* Make1;
    BSTR Model;
    char* Model1;
    BSTR SerialNumber;
    BSTR IpAddress;
    char* IpAddress1;
    BSTR Port;
    int Port1;
    BSTR LocationCode;
    } machinelist[100] ;
   int w;
 } ;

i created an object of Con class as Con m_con;

I have another class Test

class Test
{
 public:
  void fun();//i want to pass the object of the structure that i created in Con
  //what arguments should i pass in fun function?
};

Upvotes: 0

Views: 898

Answers (3)

xtofl
xtofl

Reputation: 41509

Do you want to pass the whole machinelist array?

void fun(const Con::MachineList (&argument)[100] );

But easier would be to typedef it:

class Con { 
 public:
    struct MachineList{ ... };
    typedef MachineList (Machines)[100];

    Machines machines;
};

and use

void fun(const Con::Machines& m);

To be called like:

Con c;
fun( c.machines );

Upvotes: 4

Aubin
Aubin

Reputation: 14853

class Con {
public:
   struct Machine {
      BSTR  AccountId;
      BSTR  MachineId;
      BSTR  Make;
      char* Make1;
      BSTR  Model;
      char* Model1;
      BSTR  SerialNumber;
      BSTR  IpAddress;
      char* IpAddress1;
      BSTR  Port;
      int   Port1;
      BSTR  LocationCode;
   };
   typedef Machine Machines[100];

   Machines machines;
   int      w;
};

/**
 * passing a reference to a single machine, which fun might change
 */
void fun0( Con::Machine & machine );

/**
 * passing a reference to a single machine, which fun cannot change
 */
void fun1( const Con::Machine & machine );

/**
 * passing a reference to the entire array of machines, which fun may change
 */
void fun2( Con::Machines & machines );

/**
 * passing a reference to the entire array of machines, which fun cannot change
 */
void fun3( const Con::Machines & machines );

I don't understand which version of fun you want so I have made four...

Upvotes: 2

bames53
bames53

Reputation: 88155

class Test
{
public:
void fun(Con::MachineList);
};

Test t;
Con c;
t.fun(c.machinelist[0]);

Currently the Con::MachinList type looks like it's not appropriate for copying, so you should either define appropriate constructors and assigment operators or you should pass by reference by declaring fun as void fun(Con::MachineList const &); instead of as I show above.

Also MachinList probably needs an appropriate destructor...

Upvotes: 0

Related Questions