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 Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Pass and object to a class

Status
Not open for further replies.

dd007

Technical User
Jan 7, 2003
7
US
Can someone lead me in the right direction. I am trying to pass just one instance of a class(class1) to multiple instances of another class(class2).

I tried just passing class1 to class2 in the constructor and having class2's constructor accept a class1 pointer.
Is this correct? I am having problems accessing class1 members from inside of class2.

Sorry if this is confusing. This is the basic setup I am trying to achieve.

class Class1 {

public:
int ReturnValue();

};

Class1::ReturnValue()
{
return 5;
}
class Class2{
public:
Class2(Class1 &s1);
void GetValue();

};
void Class2::GetValue()
{
cout << s1.ReturnValue();
}


int main()
{
Class1 s1;
Class2 p1(s1);

return 0;
}
 
Well, from the looks of it, you are not setting a member variable to the class. Either impliment a copy constructor for the class so you can set a member variable or use a pointer to the class.

...

class Class2{
public:
Class2(Class1 &s1);
void GetValue();
protected:
Class1* m_pClass1;
};

Class2::Class2(Class1* pClass1):
m_pClass1(pClass1)
{
}

void Class2::GetValue()
{
cout << m_pClass1->ReturnValue();
}


This is just one example.

Matt
 
Thanks for the reply Matt. I would like to use a pointer to the object approach. There is going to be about 3-4 instances of Class2, these will need to have access to one function of a single Class1 object.

Can you explain more on your code.

Class2::Class2(Class1* pClass1):
m_pClass1(pClass1)

And

protected:
Class1* m_pClass1;

Do you know any good websites that help explain interaction between classes? My textbooks does not cover interaction between classes.

Thanks
Dave

 
Class2::Class2(Class1* pClass1):
m_pClass1(pClass1)

This is a constructor, that takes a pointer to a Class 1 object as a parameter. The Class 2 member variable m_pClass1 is assigned to the parameter pClass1 (This is done using an assignment list, as opposed to writing

Class2::Class2(Class1* pClass1)
{
m_pClass1 = pClass1)
}

protected:
Class1* m_pClass1;

This creates a member variable of type pointer to Class1.

I take it you know the difference between public, private and protected ?

K
 
Thanks for the response.

Class2::Class2(Class1* pClass1)
{
m_pClass1 = pClass1
}

That cleared it up for me, thanks for the explanation.
I got it running now!



Dave
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top