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?
The code you posted is wrong.
First, to call
B‘s constructor like that,Ahas to be derived fromB.Second, you provide 2 implementations for
A::A.I’ll explain on the following example:
Now, since
Ais-aB(that’s what inheritance is), whenever you construct anA, a base object –B– will also be constructed. If you don’t specify it in the initializer list, the default constructor forB–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:If however your constructor is defined as:
B‘s default constructor will be called:Hope that’s clear.