Calling a class within a class
I am trying to write a class that, when asked, will call the class and turn it into a member of the class. Here's a quick example of what I mean:
class foo{
myClass Class;
foo();
};
foo::foo()
{
//Create the class and set it as the foo::Class variable
}
I'm sure it's actually very simple. Any help would be appreciated Thanks
Edit: Sorry for the wrong terminology. I will try to move on to what I want to do more succinctly. I am creating a class (foo) that has varaible (Class) with a class definition (myClass). I need to create an object myClass and assign it to a class, with class foo. With the help of everyone, I have achieved this.
Now my problem is that the object I created is giving me "Unhandled Exception" ... "Access reading reading location 0x000000c0" in the class on the first line of the myClass function I'm trying to execute. Thanks for your help!
Note: I am currently using emg-2 solution.
a source to share
There is no need to do anything. Assuming myClass has a default constructor, it will be used to instantiate the class (you could use better names here, you know) for you. If you need to pass parameters to a constructor, use an initialization list:
foo :: foo() : Class( "data" ) {
}
If you only want composite use Neil's solution. If you want aggregation (i.e. you are assigning external objects to the class myClass *) you must use a pointer:
class foo{
myClass * Class;
void createClass();
};
// can't use name foo, because its a name reserved for a constructor
void foo::createClass() {
Class = new myClass();
}
I'm not sure I understood the question correctly. But if you are trying to create an object on demand, you can do something like this:
class foo{
myClass* m_pClass;
foo();
myClass* f();
~foo();
};
foo::foo() : m_pClass(NULL) //Initialize the pointer to NULL do not create any object in the constructor
{
}
foo::~foo()
{
//Release the allocated object
delete m_pClass;
m_pClass = NULL;
}
myClass* foo::f()
{
//Create a new object and return
m_pClass = new myClass;
return m_pClass;
}
a source to share