(I’m sorry if this has been asked before; the search feature seems to be broken: the results area is completely blank, even though it says there are a few pages of results… in Chrome, FireFox, and Safari)
So, I’m just learning C++… and the book I’m moving through is doing a really bad job of explaining constructors in a way that I can grasp them. I’ve pretty much grokked everything else so far, but I can’t figure out how the syntax for constructors actually works.
For instance, I am told that the following will cause the constructor to call the designated superclass’s constructor:
class something : something_else {
something(int foo, double bar) : something_else(int foo) {}
};
On the other hand, that same syntax was utilized later on in the book, when describing how to initialize const
members:
class something : something_else {
private: const int constant_member;
public: something(int foo, double bar) : constant_member(42) {}
};
So… uh… what the hell is going on there? What does the syntax rv signature(param) : something_else(what);
actually mean? I can’t figure out what that something_else(what)
is, with relation to the code around it. It seems to take on multiple meanings; I’m sure there must be some underlying element of the language that it corresponds to, I just can’t figure out what.
Edit: Also, I should mention, it’s very confusing that the what
in the previous example is sometimes a parameter list (so something_else(what)
looks like a function signature)… and sometimes a constant-value expression (so something_else(what)
looks like a function call).
Now, moving on: What about multiple-inheritance and constructors? How can I specify what constructors from which parent classes are called… and which ones are called by default? I’m aware that, by default, the following two are the same… but I’m not sure what the equivalent is when multiple-inheritance is involved:
class something : something_else {
//something(int foo, double bar) : something_else() {}
something(int foo, double bar) {}
};
Any help in grokking these topics would be very appreciated; I don’t like this feeling that I’m failing to understand something basic. I don’t like it at all.
Edit 2: Okay, the answers below as of now are all really helpful. They raise one more portion of this question though: How do the arguments of base-class-constructor-calls in ‘initialization lists’ relate to the constructor you’re defining? Do they have to match… do there have to be defaults? How much do they have to match? In other words, which of the following are illegal:
class something_else {
something_else(int foo, double bar = 0.0) {}
something_else(double gaz) {}
};
class something : something_else {
something(int foo, double bar) : something_else(int foo, double bar) {} };
class something : something_else {
something(int foo) : something_else(int foo, double bar) {} };
class something : something_else {
something(double bar, int foo) : something_else(double gaz) {} };