Inheritance in C allows a derived class to inherit properties and behaviors from a base class to promote code reuse and reduce duplication. For example, classes like Enemy and Player can inherit shared functionality such as health and movement from a base Character class. C supports single, multiple, multilevel, hierarchical, and hybrid inheritance, each with distinct use cases. Access specifiers like public, protected, and private determine member accessibility in derived classes, while constructors and destructors must be explicitly called. Derived classes can override base class functions, especially using virtual functions for runtime polymorphism, enabling dynamic method resolution based on the actual object type.
Inheritance in C is a feature that allows a class (called a derived or child class) to inherit properties and behaviors (like variables and functions) from another class (called a base or parent class). This helps avoid code duplication and makes it easier to build and maintain applications.

Why Use Inheritance?
The main reason to use inheritance is code reuse. If you have two classes that share some common functionality, instead of writing the same code twice, you can create a base class with that shared code and have both classes inherit from it.

For example:
- Imagine you're building a game and have classes like
Enemy
andPlayer
. - Both might need health, position, and movement logic.
- You could create a base class called
Character
, and haveEnemy
andPlayer
inherit from it.
This way, if you update how movement works, you only have to change it in one place — the Character
class.

Types of Inheritance
C supports several types of inheritance:
- Single inheritance: One derived class inherits from one base class.
- Multiple inheritance: One derived class inherits from two or more base classes.
- Multilevel inheritance: A derived class inherits from another derived class (like a chain).
- Hierarchical inheritance: Multiple derived classes inherit from a single base class.
- Hybrid inheritance: A mix of the above types.
Each type has its own use cases. For example, multiple inheritance can be useful but also adds complexity — especially when dealing with naming conflicts or ambiguous calls.
Access Specifiers and Inheritance
When inheriting members, the access level matters. Here's what happens depending on the inheritance mode:
-
public inheritance: Members that are
public
in the base class remainpublic
in the derived class;protected
members stayprotected
. -
protected inheritance: All
public
andprotected
members becomeprotected
in the derived class. -
private inheritance: All inherited members become
private
in the derived class.
It’s important to remember that private
members of the base class are never accessible directly in the derived class, even if the inheritance is public.
Also, constructors and destructors don’t get inherited automatically. But you can call the base class constructor from the derived class using an initialization list.
Overriding Functions
A derived class can override functions from the base class — this means providing a new implementation for a function that already exists in the parent class.
To do this:
- The function must have the same name, return type, and parameters in both classes.
- If you want to support runtime polymorphism (deciding which function to call at runtime), declare the function as
virtual
in the base class.
This lets you write code like:
Character* player = new Player(); player->move(); // Calls Player's move(), not Character's
Without virtual functions, the compiler decides which function to call based only on the pointer or reference type — not the actual object type.
That’s basically how inheritance works in C . It’s powerful but needs careful handling, especially with access control and overriding behavior.
The above is the detailed content of What is inheritance in C ?. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Functions are the basic unit of organizing code in C, used to realize code reuse and modularization; 1. Functions are created through declarations and definitions, such as intadd(inta,intb) returns the sum of the two numbers; 2. Pass parameters when calling the function, and return the result of the corresponding type after the function is executed; 3. The function without return value uses void as the return type, such as voidgreet(stringname) for outputting greeting information; 4. Using functions can improve code readability, avoid duplication and facilitate maintenance, which is the basic concept of C programming.

decltype is a keyword used by C 11 to deduce expression types at compile time. The derivation results are accurate and do not perform type conversion. 1. decltype(expression) only analyzes types and does not calculate expressions; 2. Deduce the variable name decltype(x) as a declaration type, while decltype((x)) is deduced as x due to lvalue expression; 3. It is often used in templates to deduce the return value through tail-set return type auto-> decltype(t u); 4. Complex type declarations can be simplified in combination with auto, such as decltype(vec.begin())it=vec.begin(); 5. Avoid hard-coded classes in templates

C folderexpressions is a feature introduced by C 17 to simplify recursive operations in variadic parameter templates. 1. Left fold (args...) sum from left to right, such as sum(1,2,3,4,5) returns 15; 2. Logical and (args&&...) determine whether all parameters are true, and empty packets return true; 3. Use (std::cout

C's range-basedfor loop improves code readability and reduces errors by simplifying syntax. Its basic structure is for(declaration:range), which is suitable for arrays and STL containers, such as traversing intarr[] or std::vectorvec. Using references (such as conststd::string&name) can avoid copy overhead and can modify element content. Notes include: 1. Do not modify the container structure in the loop; 2. Ensure that the range is effective and avoid the use of freed memory; 3. There is no built-in index and requires manual maintenance of the counter. Mastering these key points allows you to use this feature efficiently and safely.

ABinarySearchTree(BST)isabinarytreewheretheleftsubtreecontainsonlynodeswithvalueslessthanthenode’svalue,therightsubtreecontainsonlynodeswithvaluesgreaterthanthenode’svalue,andbothsubtreesmustalsobeBSTs;1.TheC implementationincludesaTreeNodestructure

Calling Python scripts in C requires implementation through PythonCAPI. First, initialize the interpreter, then import the module and call the function, and finally clean up the resources; the specific steps are: 1. Initialize the Python interpreter with Py_Initialize(); 2. Load the Python script module with PyImport_Import(); 3. Obtain the objective function through PyObject_GetAttrString(); 4. Use PyObject_CallObject() to pass parameters to call the function; 5. Call Py_DECREF() and Py_Finalize() to release the resource and close the interpreter; in the example, hello is successfully called

References are alias for variables, which must be initialized at declaration and cannot be rebinded. 1. References share the same memory address through alias. Modifying any name will affect the original value; 2. References can be used to achieve bidirectional transmission and avoid copy overhead; 3. References cannot be empty and have the grammar, and do not have the ability to repoint compared to pointers; 4. ConstT& can be used to safely pass parameters, prevent modification and support binding of temporary objects; 5. References of local variables should not be returned to avoid dangling reference errors. Mastering citations is the key foundation for understanding modern C.

First, let’s clarify the answer: This article introduces the use of fstream in C, including basic file read and write operations and advanced bidirectional read and write functions. 1. Use std::fstream to define the file flow object, and open the file in a specified mode (such as std::ios::out, std::ios::in); use it when writing
