user707549
user707549

Reputation:

c++ Initializer list

I have a question about c++ Initializer list, I see the following code somewhere:

class A {
public:
  A(String sender, String receiver, String service) {
                                                        //do something here
                                                    }
}

class B {
public:
  B(String sender, String receiver, String service) {
                                                        //do something here
                                                    }
}

Then the object is created in the following way:

A::A(sender,receiver, service) : B(sender,receiver, service) {
//do something here
}

does B will also be created based on the paramaters passed? How could this happen?

Upvotes: 0

Views: 409

Answers (1)

Luchian Grigore
Luchian Grigore

Reputation: 258548

The code you posted is wrong.

First, to call B's constructor like that, A has to be derived from B.

Second, you provide 2 implementations for A::A.

I'll explain on the following example:

class B
{
   int _x;
public:
   B();
   B(int x);
}

B::B()
{
   _x = 42;
}
B::B(int x)
{
   _x = x;
}

class A : public B
{
public:
    A(int x);
};

A::A(int x) : B(x) {}

Now, since A is-a B (that's what inheritance is), whenever you construct an A, a base object - B- will also be constructed. If you don't specify it in the initializer list, the default constructor for B - B::B() will be called. Even though you don't declare on, it does exist.

If you specify a different version of the constructor - like in this case, B::B(int), that version will be called.

It's just the way the language is designed.

EDIT:

I edited the code a bit.

Assume the following definition of A's constructor:

A::A(int x) : B(x) {}
//...
A a(10);
//a._x will be 10

If however your constructor is defined as:

A::A(int x) {}

B's default constructor will be called:

A a(10);
//a._x will be 42

Hope that's clear.

Upvotes: 5

Related Questions