Pointer to class

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • kiberg
    New Member
    • Jul 2007
    • 12

    Pointer to class

    hi,

    Code:
    class A
    {
     int i;
    }
    
    class B
    {
     A *a;
     int number;
    
     B(A obj){
     a=&obj;
     number=*a.i;//ERROR:
    }
    
    }
    ERROR: request for member `i' in `B:a', which is of non-aggregate type `A *'

    What's the problem?
  • Banfa
    Recognized Expert Expert
    • Feb 2006
    • 9067

    #2
    Apart from missing the ; from the end of both classes you have an operator preceedence error in
    [code=cpp] number= *a.i; // ERROR:[/code]

    The . operator (Member access from an object) has higher preceedence than * (Dereference) so this is interpreted as

    [code=cpp] number= *(a.i); // ERROR:[/code]

    and since a is not a structure, class or union (it is a point to a aclass) this is not valid.

    You can fix this error by adding parenthises to make the * operator evaluated first

    [code=cpp] number= (*a).i;[/code]

    or better still you can use the Member access from a pointer operator, ->

    [code=cpp] number= a->i;[/code]

    Eliminating any conflict since there is now only 1 operator (you could also use the array access operator but since it is not an array I would say this would be bad form).

    When you have done this you will get another error because a->i tries to access i which is a private member of A and therefore not accessible in B.

    When you have fixed that then the code will compile but will likely cause segmentation faults at some point because you point B::a at a temporary copy of an A object that exists on the stack while the constructor is running but is deleted once the constructor exits resulting in an invalid pointer.

    Comment

    Working...