Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Wanet Telecoms Ltd on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

pointer to an instance of a different class

Status
Not open for further replies.

xlix

Programmer
Jul 24, 2003
2
US
This is what I have in hand as of now:
class classA
{
public:
int classtype;
int dummy;
void * pObj;
};

class classB
{
public:
int classtype;
int dummy;
};

classA iclassA[20];
classB iclassB[20];


int main()
{
iclassA[0].pObj = (void *) &iclassB[0];
iclassB[0].dummy=5;
system("PAUSE");
return 0;
}

Here void * pObj is an attribute of classA that points to an instance of classB namely iclassB[0]. What I would like to know is how I can assign the value of an attribute of the instance iclassB[0] to an attribute of the instance iclassA[0] that holds pObj.

Shall appreciate all input.
 
This works for me:

void * r = static_cast< void * >( new char[15] );

strcpy( static_cast< char * >( r ), &quot;string value&quot; );

cout << static_cast< char * >( r ) << endl;

delete [] r;


Does that help?
 
If pObj is always intended to be a ponter to an instance of classB, then the following will also work for you...

Code:
class classB; //forward reference

class classA
{
 public:
 int classtype;
 int dummy;
 classB * pObj;
};

class classB
{
 public:
 int classtype;
 int dummy;
};

classA iclassA[20];
classB iclassB[20];


int main()
{
      iclassA[0].pObj = &iclassB[0];
      iclassB[0].dummy=5;
      iclassA[0].dummy = iclassA[0].pObj->dummy;

      return 0;
}
 
federal102, thanks for your response. I was wondering if it was possible for me to have pObj open to be able to point to instances of other classes too instead of being restricted to just classB. Can you please offer me a suggestion on this?
 
Under your current scenario, I cannot think of a solution other than a void pointer. In general though, the use of void pointers in C++ is indicative of a design flaw.

What are you trying to achieve?
 
Do you want to use the pointer on a specific type of class, or on any class imaginable?

If the classes you intend to use the pointer on are related, then your best bet is to use inheritance, and polymorphism.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top