0

Mega-newb question, which I simply cannot find an answer to on google.

Say, I have the following class:

class A {
private:
B b;
public:
A();
};

How would I go about constructing b inside A's constructor? Can I just do:

A() {
b();
}

or what?

Thanks in advance.

Sunspawn
  • 817
  • 1
  • 12
  • 27
  • 2
    @PravasiMeet: It's generally not a good idea to leave things uninitialized. Although in the case of a POD it is a good idea to have that possibility. Hm, your question was deeper than I thought. Anyway. In this case it's unavoidable, there will automatically be an initialization, assuming B is a class type. – Cheers and hth. - Alf Nov 27 '15 at 17:33
  • 1
    @LightnessRacesinOrbit I knew what an initialization list was, but due to previously seeing it used only with primitives, did not realize it was actually constructing them with the given values. In fact, the fact that something like integers or characters can be constructed is news to me. – Sunspawn Nov 27 '15 at 17:35

1 Answers1

3

Look for initializer lists (http://en.cppreference.com/w/cpp/language/initializer_list):

A() : b(...) { }

B is default constructed by default. You need to do this only if you are going to need something different from default constructor.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
simpel01
  • 1,792
  • 12
  • 13