Home > Backend Development > C++ > How to Call a Base Class Constructor in C ?

How to Call a Base Class Constructor in C ?

Linda Hamilton
Release: 2024-11-26 08:23:08
Original
548 people have browsed it

How to Call a Base Class Constructor in C  ?

Calling the Base Class Constructor

While working with inheritance in Java, you can invoke the superclass constructor using super(). This raises the question of how to achieve the same functionality in C .

Specifically, the issue arises when inheriting from a C base class with a non-default constructor. The compiler often warns about the lack of an appropriate default constructor.

Solution: Utilizing the Constructor's Initializer List

Unlike Java, C does not have an explicit super() syntax for calling the base class constructor. Instead, you specify the call in the constructor's initializer list of the derived class. The initializer list appears before the body of the constructor and is used to initialize member variables.

For example, consider the following base class with a constructor that takes a character array as an argument:

class BaseClass {
public:
    BaseClass(char *name);
    ...
};
Copy after login

To call the base class constructor in the derived class, include the call in the initializer list:

class Foo : public BaseClass {
public:
    Foo() : BaseClass("asdf") {}
};
Copy after login

This ensures that the base-class constructor is invoked before any other member initialization occurs. As the base-class constructors take arguments, they must be specified in the initializer list before any member variables are initialized.

The above is the detailed content of How to Call a Base Class Constructor 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template