tags:

views:

260

answers:

5

Hello, I'm wondering if it's possible to pass a class as a parameter in c++. Not passing a Class Object, but the class itself which would allow me to use this class like this.

void MyFunction(ClassParam mClass)
{
    mClass *tmp = new mClass();
}

The above is not real code, but it hopefully explains what I'm trying to do in an example.

+2  A: 

You are looking for templates

Yannick M.
+16  A: 

You can use templates to accomplish something similar (but not exactly that):

template<class T>
void MyFunction()
{
    T *tmp = new T();
}

and call it with MyFunction<MyClassName>().

Note that this way, you can't use a "variable" in place of T. It should be known at compile time.

Mehrdad Afshari
+12  A: 

C++ does not store meta data about classes as other languages do. Assuming that you always use a class with a parameterless constructor, you can use templates to achieve the same thing:

template <typename T>
void MyFunction
{
    T* p = new T;
}
Andy
<quote>As other lanaguages</quote> Not all languages store meta data about the program. This is a relatively new feature of modern languages.
Martin York
@Martin, that is an interesting definition of "relatively new", considering that Smalltalk, which was fairly mainstream in its time, and had quite a bit of code written in it, did just that in the 70s :)
Pavel Minaev
As with many things attributed to Smalltalk, Lisp was there in the 1950s - the entire program was a datastructure which could be inspected and manipulated.
Pete Kirkham
A: 

You can create a static factory method on your class(es) that simply returns a new instance of the class and then you can pass around pointers to that function similarly to what you want to do in your example. Return types are covariant, so if all your classes implement the same interface, you can have the function pointer return that interface. If they don't all have a common interface, you'll probably be left with returning void *. Either way, if you need to use the specific subclass, you'll have to dynamic_cast.

rmeador
+1  A: 

You could also pass in a function pointer that when called creates an instance of whatever you want and returns that.

void MyFunction(ClassCreatorPtr makeClassFn)
{
    void * myObject = makeClassFn();
}

You'd need to have it return a pointer to a base class to do anything really interesting with it.

Norman