Resorter Resorter - 2 months ago 6
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:
CLS::CLS();

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

How do I do this?

Answer

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 {
 public:
   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 {
 public:
   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.