1

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?

9
  • 2
    You can use Foo x = {blah, blah};. Commented Jul 6, 2019 at 12:58
  • 1
    By the way, your "initialization by assignment" is called copy-initialization. Commented Jul 6, 2019 at 12:58
  • 2
    Are you passing -std=c++11 to the compiler? Commented Jul 6, 2019 at 13:02
  • 1
    cls(int b){a=b;cout<<"Constructor with parameter called";} --> cls(int b) : a(b) {cout<<"Constructor with parameter called";} - you want to initialize a in the initialization list, not default initialize it first and then subsequently assign to it in the constructor body. That's wasteful and won't even work for types that cannot be default constructed or cannot be assigned to. Commented Jul 6, 2019 at 13:04
  • 1
    @trisct Copy-initialization is a standard term-of-art that doesn't directly relate to copy constructors. Commented Jul 6, 2019 at 13:08

1 Answer 1

1

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;
}
Sign up to request clarification or add additional context in comments.

7 Comments

So what exactly is the difference between using () and {} here?
I don't think you understand the question. This isn't copy-initialization.
@L.F. this is direct initialization, isn't it?
@ElProfesor Yes.
@trisct {} is a list initialization you can change it to copy initialization by using cls t = {a, b};
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.