Initializer List question

I know that if we have primitive data types like int x, then we can simple use : x(0) to initialize it to 0 in the initializer list, but what if we have an object from another class, do we initialize it to it's constructor in the intializer list? For example...

1
2
3
4
5
6
7
8
9
10
11
12
13
  Class A {
   public:
    A();
   ~A();
  };

  Class B {
    public:
     B();
    ~B();
    private:
     A test;
  };


Here we have two classes, and class B has an object of type Class A. So in the initializer list would we call

1
2
3
4
  B() : test(A())
  {

  }


I can't think of any other way to initialize an object data type in an internalizer list
Last edited on
How about just
 
B() { }

A's constructor will be called automatically.

If you need to pass an argument then:
 
B(int n) : test(n) { }

Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>

struct A {

   A() = default ; // default constructor
   A( int, int ) { /* ... */ } // 2-arg constructor

   // ...
};

struct B {

    B() {} // test is default-constructed (we don't need to do anything for that)

    B( int x, int y ) : test(x,y) {} // initialise test using its 2-arg constructor

    A test ;
};
Last edited on
So what you're saying is if the constructor for A doesn't take any parameters then I can just omit it from the initializer list?
@JLBorges, Is there an advantage to saying
A() = default;
over
A() {}
?

Another little example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>

class Int {
    int n;
public:
    Int(int n = 0) : n(n) {}
    int get() { return n; }
};

class Data {
    Int x;
public:
    Data() {}
    Data(int n) : x(n) {}
    void print() { std::cout << x.get() << '\n'; }
};

int main() {
    Data d, e(42);
    d.print();
    e.print();
    return 0;
}

Last edited on
With A() = default; the constexpr and noexcept specifiers are added automatically (if warranted).
With /* constexpr */ A() /* noexcept */ {}, this has to be done by the programmer.

Other than that, there is no difference.
I'm more confused now than I was before I asked the question. Do I need to initialize an object or not? And if so, then how is that done when using an initializer list?
Last edited on
> So what you're saying is if the constructor for A doesn't take any parameters then
> I can just omit it from the initializer list?

Yes.
Topic archived. No new replies allowed.