Is it possible to pass a class as an argument of a function in C++

Short answer: no.

You can’t pass a class as an argument to a function. You can only pass a value. A value refers to either an object or a function.

You can pass a class as an argument to a template. However, template arguments must be determined at compile-time, not run-time.

C++ provides run-time polymorphism only through inheritance. If you want to create an object whose type will not be known until run-time, what you can do is to make all possible types you might want to create derived classes of a common base.

Even still, you can’t use the type itself, that you want to create, as an argument to a function. You’ll have to pass in some other value and then branch on that to determine which type you want to create at run-time.

Leave a Comment