When you say
int foo;
or
MyClass bar;
you are
creating a new object.
The code you have posted will make it so that MyClass contains a SubClass object... but then the SubClass object will contain
another MyClass object, which contains another SubClass object, etc, etc, etc.
So clearly that is not what you want.
Instead, you want to access an existing object that was created elsewhere. For this, you can use a pointer. Pointers are not objects themselves, but instead "point to" an existing object.
1 2 3 4 5 6 7 8 9 10 11 12 13
|
class Subclass
{
MyClass* owner; // <- The * makes it a pointer
//...
}
void SubClass::DoSomething()
{
// now, assuming 'owner' has been initialized properly,
// you can access your owner's 'something' member like this:
owner->something = 1234.5678f;
}
|
The MyClass object will then need to tell the SubClass who the owner is (ie: it will need to provide that pointer. You can probably do this in the MyClass constructor:
1 2 3 4
|
MyClass::MyClass()
{
mySubClass.owner = this; // tell the sub class that 'this' is the owner
}
|
EDIT:
Ninja'd by EssGeEich. Inheritance is another way to go, but has different implications. Are you trying to derive a class? Or is this an owner/owned relationship?
To clarify: Inheritance replies an "is a" relationship. The parent class represents a generic type, and the derived class represents a more specialized version of that type.
For example:
Parent class Vehicle might have derived classes Car, Boat, Airplane, etc.
Parent class Dog might have derived classes Poodle, Pug, etc.
On the other hand, ownership implies that one object owns another... like the smaller class is a part in a larger machine.
For example:
Owner class Car might have owned classes Engine, Windshield