Search code examples
c++classconstructorconstructor-overloading

How to check what constructor overload is used


If I have a class constructor with two overloads taking in different inputs, is there a way to tell them apart? For example,

class example
{
    double ExampleDouble;
    char ExampleChar;
    public:
    example(double ED)
    {
        ExampleDouble=ED;
    }
    example(char EC)
    {
        ExampleChar=EC;
    }
};
int main()
{
    example var('a');
    return 0;
}

Is there any way to tell whether "var" is storing a double or char?

I tried using var.ExampleChar but it threw an error, and there were no online resources regarding this issue.


Solution

  • The simple way would be to do something like this

    class example
    {
    public:
        double ExampleDouble;
        char ExampleChar;
        bool IsChar;
        example(double ED)
        {
            ExampleDouble=ED;
            IsChar=false;
        }
        example(char EC)
        {
            ExampleChar=EC;
            IsChar=true;
        }
    };
    

    But you are reinventing the wheel. The class you have here is similar to what std::variant already does for you.

    #include <variant>
    #include <iostream>
    
    int main()
    {
        std::variant<double, char> var('a');
        if (holds_alternative<char>(var))
            std::cout << "its a char\n";
        return 0;
    }