Gentoo Forums
Gentoo Forums
Gentoo Forums
Quick Search: in
C++ passing class instance as another class's member - help
View unanswered posts
View posts from last 24 hours

 
Reply to topic    Gentoo Forums Forum Index Portage & Programming
View previous topic :: View next topic  
Author Message
Duncan_L
n00b
n00b


Joined: 06 Sep 2008
Posts: 42

PostPosted: Sun Sep 21, 2008 2:06 am    Post subject: C++ passing class instance as another class's member - help Reply with quote

Code:
#include <iostream>
using std::cout;
using std::cin;
using std::endl;

struct myClassA
{
  int* my_array; //getting read to make a dynamically allocated array

  myClassA()
  {my_array=new int[5];} //dynamically allocates array, my_array, with arbitrary size 5

};//end of myClassA structure

struct myClassB
{
  myClassA* pt; //I want to be able to use an instance of myClassA as a member in myClassB. I intend to pass it via the constructor.
  myClassB(myClassA* myPt) //Constructor takes pointer to instance of myClassA
  {pt=myPt;} //I set myClassB's member, pt, to the pointer passed as an argument in the constructor

  void myMethod()
  {cout<<*pt.my_array[2]<<endl;} //theoretically this should work right??
  //error: request for member 'my_array' in '((myClassB*)this)->myClassB::pt', which is of non-class type 'myClassA*'
};

int main()
{return 0;}


Can anybody help fix the error I'm getting? (It's a few lines from the end)
Back to top
View user's profile Send private message
timeBandit
Bodhisattva
Bodhisattva


Joined: 31 Dec 2004
Posts: 2719
Location: here, there or in transit

PostPosted: Sun Sep 21, 2008 3:42 am    Post subject: Reply with quote

It's a common C pitfall--a simple matter of operator precedence. You need to write either (*pt).my_array[2] or pt->my_array[2].

The dot operator has higher precedence than the dereference operator (*). As written, you've attempted to access a member (my_array) of a pointer, which is of course impossible. Use parentheses to force the pointer dereference to be evaluated first: (*pt). Then you can access members of the pointed-to structure. This is such a common idiom that the language provides an additional operator (->) for the purpose.
_________________
Plants are pithy, brooks tend to babble--I'm content to lie between them.
Super-short f.g.o checklist: Search first, strip comments, mark solved, help others.
Back to top
View user's profile Send private message
Duncan_L
n00b
n00b


Joined: 06 Sep 2008
Posts: 42

PostPosted: Sun Sep 21, 2008 6:48 am    Post subject: Reply with quote

oh, cool thanks.
Back to top
View user's profile Send private message
Display posts from previous:   
Reply to topic    Gentoo Forums Forum Index Portage & Programming All times are GMT
Page 1 of 1

 
Jump to:  
You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot vote in polls in this forum