Search code examples
c++classconstructorinitializationassignment-operator

Initialization of a class object by assignment


I was doing some experiment today with the constructors:

class cls
{
    int a;
public:
    cls(){cout<<"Default constructor called\n";}
    cls(int b){a=b;cout<<"Constructor with parameter called";}
}

Then this kind of initialization

cls x=5;

yields an output saying that the constructor with parameter has been called.

My question i: what if I have a constructor with two or more parameters? Can I still use the initialization by assignment?


Solution

  • you can do the same with more parameters like this:

    #include <iostream>
    
    class cls
    {
        int a;
        double b;
    public:
        cls(){std::cout<<"Default constructor called\n";}
        cls(int a): a(a){std::cout<<"Constructor with parameter called";}
        cls(int a, double b) : a(a), b(b){std::cout<<"Constructor with two parameter called";}
    };
    
    int main()
    {
        cls t = {1, 1.5};
        return 0;
    }