Home > Enterprise >  Is it possible to have a constructor with 1 input parameter of undeclared type?
Is it possible to have a constructor with 1 input parameter of undeclared type?

Time:12-29

Here is what I an trying to do:

  1. Class with two objects (string myStr and int myInt)

  2. Constructor takes in 1 parameter (data type not fixed).

  3. If parameter is string: myStr = parameter; myInt = parameter.length();

  4. If parameter is int: myInt = parameter; myStr = "0000...0" (string of length "parameter", set by for loop)

  5. Else : cout << "Error";

Is it possible to do what I am describing in line 2?

I've managed to do some workarounds using only strings and converting data types (able to do this when imposing an artificial lower bound for length of myStr) however this is causing me other issues further down the line.

CodePudding user response:

Is it possible to have a constructor with 1 input parameter of undeclared type?

Technically, you can have variadic parameters which allows unspecified number of arguments of unspecified types. But I recommend against using it.

The types of all other parameters must be declared.

  • If parameter is string: myStr = parameter; myInt = parameter.length();

  • If parameter is int: myInt = parameter; myStr = "0000...0" (string of length "parameter", set by for loop)

You can easily achieve this using two constructors instead of one. One that accepts a string and another that accepts an integer.

CodePudding user response:

The issue is not using a single parameter, but that you need later to find out the type of data of the parameter.

A commonly used trick it's to use either a generic Pointer, or a generic object class reference or Pointer.

MyClass::MyClass ( void* P );
MyClass::MyClass ( SomeBaseClass& P);

Since You are working for more simple data, You may want to try an O.O. approach like nesting the values in objects, and later, checking the type of the data:

class BaseClass
{
  // ...
} ;

class IntegerClass: BaseClass
{
  int Value;
} ;

class StringClass: BaseClass
{
  String Value;
} ;

And your class can receive a "BaseClass" object reference:

class MyClass
{
  private int MyInt;
  private String MyString;
  
  MyClass ( BaseClass& P ) 
  {
     if ( P is IntegerClass )
     {
       // 
     }
     else if ( P is StringClass )
     {
       //
     }
  }
} ;

int main (...)
{
  IntegerClass *i = new IntegerClass(5);
  StringClass *s = new StringClass ("Hello");
  
  MyClass *O1 = new MyClass(i);
  MyClass *O2 = new MyClass(s);
  
  // Display values of O1 and O2 here
  
  free O2;
  free O1;
   
  free s;
  free i;
  
  return 0;
}

Just my two bitcoins ...

  • Related