Fedor Semenov wrote:
How can I call a base class' constructor from a derived class. Suppose I
have:
class Button // Base class
{
public:
Button(void)
{
// Register classes, create the button, etc.
}
};
class MyButton : public Button // Derived class
{
public:
MyButton(void)
{
// Customize title, size, etc.
// How do I call Button's (base class) constructor here?
}
};
Its impossible to create an object of type MyButton above if MyButton's
ctor is unable to invoke a base class' ctor.
You can't call a ctor. Or rather: you definitely wouldn't want to even
if you could. invoking means 'accessing something that is already
available but not over-rideable'. A 'call' implies something you can
overide.
I'm not allowed to redefine the Button() ctor within the MyButton class.
That can only be done from within the Button class. Thats why call !=
invocation.
Hence, the above MyButton class is actually:
class MyButton : public Button
{
public:
MyButton() : Button() // the defaults
{
}
};
Test it. Change the base class to:
class Button
{
int width;
public:
Button(int n) : width(n) { }
};
and the MyButton class can no longer generate an instance.
.... unless ...
class MyButton : public Button
{
public:
MyButton() : Button(100)
{
}
};
___
Alternatively, here is a MyButton object with a preset width of 100:
class Button
{
int width;
public:
Button() : width(100) { } // a default ctor !!!
};
class MyButton : public Button
{
public:
MyButton() // no problem, a default Button() is available
{
}
};
int main()
{
MyButton button; // width = 100, the default
}
and nothing is stopping you from providing additional ctors to invoke.
class Button
{
int width;
public:
Button() : width(100) { }
Button(int n) : width(n) { }
};
class MyButton : public Button
{
public:
MyButton() { }
MyButton(int n) : Button(n) { }
};
int main()
{
MyButton button; // width = 100, the default
MyButton anotherbutton(200); // width = 200
MyButton yetanotherbutton(480); // width = 480
}