Calling the Base Class Constructor in C
Unlike Java's super() keyword used for invoking the base class constructor, C provides a different mechanism. Let's explore how to call the base class constructor with arguments in C .
Problem:
Consider a C class with a default constructor that takes arguments, like:
class BaseClass { public: BaseClass(char *name); .... };
When inheriting from this class, one might encounter a warning about the lack of an appropriate default constructor.
Solution:
C allows the base class constructor to be called within the initializer list of the subclass's constructor. Here's an example:
class Foo : public BaseClass { public: Foo() : BaseClass("asdf") {} };
In this example, when the Foo constructor is invoked, it initializes the base class BaseClass using the constructor that takes a character pointer argument, passing the string "asdf" as the argument.
Additional Note:
Base-class constructors that require arguments must be called in the initializer list before any members of the subc lass are initialized.
The above is the detailed content of How Do I Call a Base Class Constructor with Arguments in C ?. For more information, please follow other related articles on the PHP Chinese website!