0

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?

2
  • 5
    Something is wrong. Did you mean class B : public A { instead of class B {? (Or vice versa with the classes in the other order? Or something like that.) Commented Feb 6, 2012 at 10:30
  • btw. what you mean is (c++ grammar) the ctor-initializer, or mem-initializer-list. Calling it "initializer list" might lead to confusion with initializer-list which is "the stuff in {} to initialize aggregates (and more in C++11)" Commented Feb 6, 2012 at 10:31

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

Comments