Home > Backend Development > C++ > body text

How Do I Call a Base Class Constructor with Arguments in C ?

DDD
Release: 2024-11-22 13:39:24
Original
738 people have browsed it

How Do I Call a Base Class Constructor with Arguments in C  ?

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);
    .... 
};
Copy after login

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") {}
};
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template