I'm trying to write a class that when asked on, will call on a class and make it into a class member. 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 this is actually an easy thing to do. Any help would be appreciated Thanks
Edit: Sorry for the bad terminology. I'll try to go over what I want to do more concisely. I'm creating a class(foo), that has a varaible(Class) with the class definition of (myClass). I need to create a myClass object and assign it to Class, with-in the class foo. Through the help of everyone, I have kind of achieved this.
My problem now is that the object I created gives me a "Unhandled Exception"..."Access violation reading location 0x000000c0" in Class, on the first line of myClass's function that I'm trying to execute. Thanks for your help!
note: I'm currently using emg-2's solution.
There is no need to do anything. Assuming that myClass has a default constructor, it will be used to construct the Class (you could use better names here, you know) instance for you. If you need to pass parameters to the constructor, use an initialisation list:
foo :: foo() : Class( "data" ) {
}
If you only want to composite, use Neil solution. If you want an aggregation (i.e. you will assign outside objects to myClass*Class), you should 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 am not sure I understood the question correctly. But if you are trying to create an object on demand then 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;
}
User contributions licensed under CC BY-SA 3.0