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.
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.
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.
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.
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; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With