views:

30

answers:

2

(I'm not sure if that title is worded correctly, as I'm still new to C++)

I have two classes, loosely represented here:

class SuperGroup
{
public:
    LayoutObj theLayout;
}

class SomeClass
{
public:
    LayoutObj myLayout;
    SuperGroup myGroup;
}

During SomeClass's constructor, I want to set myGroup.theLayout to be pointing to SomeClass's searchLayout. Something like this:

SomeClass::SomeClass()
{
    myGroup.theLayout = &myLayout;
}

Am I doing this correctly? Or do I need to be using a pointer? My code seems to compile okay, but when I execute it, it crashes, and I can tell its something to do with this assignment. Also, I'm not sure if its incorrectly coded, or if the SDK/API I'm using simply doesn't like it.

The reason I'm trying to reference myLayout with SuperGroup is because I have many methods in SuperGroup that need to use myLayout from SomeClass. I'm simply trying to avoid having the pass myLayout by reference into those methods every single time. Make sense? Is there an easier way to accomplish this?

+1  A: 

You do indeed need a pointer. Try using:

LayoutObj *theLayout;

Without a pointer, you are trying to assign a LayoutObj to a memory address. This may compile, but is not the behavior you want. Instead, you need a pointer to point to the memory address of a LayoutObj.

The line myGroup.theLayout = &myLayout; remains the same.

As always is the case with C++, be careful that myLayout does not go out of scope before theLayout. If this happens, you have a dangling pointer. If there is any risk of this, consider using a smart pointer of some kind, or otherwise modify your design to accommodate this.

Justin Ardini
That makes sense. Now, when I compile, anywhere that I try to do this, I get an error: myGroup.theLayout.whatever = something;error C2228: left of '.whatever ' must have class/struct/union. It's like its not letting me access the members of theLayout since its a pointer...
Jakobud
@Jakobud: With pointers, you must use `->` instead of `.` (`ptr->foo` is equivalent to `(*ptr).foo`, you need to deference the pointer to use it).
Justin Ardini
Ahh yes of course. Thanks!
Jakobud
No problem. Good luck!
Justin Ardini
A: 

Yes, you would need to use a pointer: LayoutObj *theLayout;

In reference to your last paragraph, I would consider the some alternative designs, such as:

  • Requiring that the LayoutObj is passed into each method of SuperGroup, therefore decoupling the particular LayoutObj acted upon from the actions that can be performed, or
  • Moving those methods to SomeClass, if they're not needed elsewhere, or
  • Making them methods of LayoutObj itself.
Nick Meyer