user8389676
user8389676

Reputation:

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?

Upvotes: 1

Views: 75

Answers (1)

Oblivion
Oblivion

Reputation: 7374

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;
}

Upvotes: 1

Related Questions