Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Passing a class as a parameter

Tags:

c++

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.

like image 796
Undawned Avatar asked Sep 24 '09 22:09

Undawned


People also ask

Can I pass a class as a parameter in C++?

Passing and Returning Objects in C++ In C++ we can pass class's objects as arguments and also return them from a function the same way we pass and return other variables.

How do you pass parameters to a class?

Passing by reference enables function members, methods, properties, indexers, operators, and constructors to change the value of the parameters and have that change persist in the calling environment. To pass a parameter by reference with the intent of changing the value, use the ref , or out keyword.


2 Answers

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.

like image 62
mmx Avatar answered Sep 25 '22 00:09

mmx


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; } 
like image 26
Andy Avatar answered Sep 27 '22 00:09

Andy