I am a very beginner with C++ and object-oriented programing. I am reading some books, but several points are still obscure. It would be nice if I can have your comments.
Thank you for your helps, in advance.
Regarding the children class of a mother class, I don't understand why children classes need to call the void-constructor from its mother (implicitly)? On the other hand, that should always be done by a compiler without any requirement from programers if we can never change the way the child calls its mother's void constructor? Or can we change the way it calls, somehow?
The constructor performs any initialization that is required to construct a valid object of the particular class.
The child instance is also a valid instance of the mother class, so it follows that the mother part must be properly constructed.
And you can call a different constructor of the base class using the initializer list:
The idea is that a derived class is the base class with some stuff tacked on. So on construction, the base class must be constructed before the derived part, and the reverse on destruction.
You don't need to call the base class default constructor by yourself, but you can. A call to the standard constructor will be inserted by the compiler, if you don't do it yourself.
However, you need to call a base class constructor if there is no default constructor or if the default constructor cannot be called (e.g. because its private).
struct Base
{
Base() {} // default constructor
Base(int,int) {} // not a default constructor
};
struct Derived : Base
{
Derived() {} // the compiler will insert a call to Base() for you.
Derived(float) : Base() {} // you can call the base constructor, if you like. But that's not necessary
Derived(int) : Base(1,2) {} // you can call another constructor from the base by yourself
};
// ...
class OtherBase
{
OtherBase() {} // private default constructor
public:
OtherBase(int) {} // non-private non-default constructor
};
struct OtherDerived : OtherBase
{
// you HAVE to call some base constructor here, as the default constructor is private.
OtherDerived() : OtherBase(1) {}
};
Thank you Athar, kbw, imi for your comments.
It works now with the ways Athar and imi gave.
So I understand that the default constructor, though there is no statement inside, it still "does something"... I will check more today, and if something arises I would wish to have your helps again. Thanks.