Resorter Resorter - 26 days ago 4x
C++ Question

In C++, how to make it such that the constructor can have different types of arguments?

I want to define a constructor for a class CLS. And I want to include different situations in my definition of the constructor. For example, I want the constructor to work when the argument is void:

or when the argument is an integer,
CLS::CLS(int a);

How do I do this?


Your question actually is too generic, in my opinion.

A general answer is function overloading.

In short you can simply write two different function (method in that case) with the same name, but different argument. You can specify a different body for each of them. For example:

class CLS {
   CLS(int n) {
     // do something

   CLS(char c) {
     // do something else

Then you can simply construct an object:

// ... somewhere
CLS object1(12);  // 12 is a int, then the first 'ctor will be invoked
CLS object2('b');  // 'b' is a char, the second 'ctor will be invoked, instead.

A "move advance" answer requires the usage of template.

In short you can write a single constructor which accept a generic type as argument and specify a behaviour in case that type follow certain traits.

class CLS {
   template<typename T>
   CLS(T t) {
     if (std::is_arithmetic<T>::value) {
       // do something if the type is an arithmetic
     } else {
       // do something else

That approach could be useful when you can "generalize" (for almost all the body) the behaviour of your constructor, and you want to aggregate different type.