Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading