Search code examples
c++classconstructorinitialization

Can I make a constructor in C++ of different data types?


I have a class which has multiple data members of different data types. I was wondering if I can create and initialize an object using a constructor.

class test
{
     public:
            int a;
            string b;
            float c;

      test (int x, string y, float z);

};


int main()
{

    test t1(10,"Hello",2.5f); //this line doesn't work

}


Solution

  • The fact that it doesn't work is not really what we do on StackOverflow. You should provide an error message.

    With that said, I suppose you are getting an error from the linker because your constructor does not include a definition, but only a declaration.

    Here's a working example: https://godbolt.org/z/r89cf86s3

    #include <string>
    
    class test
    {
    public:
        int a;
        std::string b;
        float c;
    
        test (int x, std::string y, float z) : a{x}, b{y}, c{z}
        {}
    };
    
    
    int main()
    {
        test t1(10, "Hello", 2.5f);
    }
    

    NOTE Passing std::string by value to the constructor can lead to temporary objects being created, so to keep the workings of this code and improve it, you could use a const-reference, i.e. const std::string& as parameter of the constructor.