Menu
Inheritance in C++

Inheritance in C++

๐ŸŽฅ C++ Inheritance: Complete Guide with Examples | Playlist

Playlist Link: C++ Series by TheCherno


๐Ÿ“š Introduction to Inheritance

Video Reference: Start at 0:00
Inheritance allows code reuse by creating a hierarchy of classes. A base/parent class (e.g., Entity) holds common functionality, and derived/child classes (e.g., Player) extend it with new features.

๐Ÿ› ๏ธ Why Use Inheritance?

  • Avoid code duplication (e.g., x, y, Move() in Entity and Player).
  • Create logical class relationships (e.g., โ€œA Player is an Entityโ€).

๐Ÿงฉ Example: Base Class (Entity)

Video Reference: 1:18

class Entity {  
public:  
    float x, y;  

    void Move(float xa, float ya) {  
        x += xa;  
        y += ya;  
    }  
};  

Derived Class (Player)

Video Reference: 2:48

class Player : public Entity {  // Inherit from Entity  
public:  
    const char* name;  

    void PrintName() {  
        std::cout << name << std::endl;  
    }  
};  

โœ… What Player Inherits:

  • All public/protected members of Entity (x, y, Move()).
  • Can add new members (name, PrintName()).

โš ๏ธ Key Points:

  • Use public inheritance to preserve access modifiers.
  • No direct access to private members of the base class (use protected instead).

๐Ÿ–ฅ๏ธ Using Inheritance in Code

Video Reference: 3:25

int main() {  
    Player player;  
    player.x = 5.0f;  // Inherited from Entity  
    player.y = 3.0f;  
    player.Move(1.0f, -1.0f);  // Inherited method  
    player.name = "Cherno";     // New member  
    player.PrintName();         // New method  
}  

๐Ÿ” Memory Layout & Type Hierarchy

Video Reference: 5:00

  • A Player object contains all members of Entity + its own members.
  • Type Checking:
    Player* player = new Player();  
    Entity* entity = player;  // Valid (Player IS AN Entity)  
    

๐Ÿ›‘ Common Pitfalls

  1. Access Specifiers:
    • Use protected for base class members if derived classes need direct access.
      class Entity {  
      protected:  // Accessible to derived classes  
        float x, y;  
      };  
      
  2. Slicing:
    • Storing a derived class object in a base class variable cuts off derived members.
      Entity entity = player;  // Only Entity members are copied!  
      

๐Ÿ“Œ Key Takeaways

  1. Inheritance reduces code duplication by sharing common logic.
  2. Use public inheritance for โ€œis-aโ€ relationships (e.g., Player is an Entity).
  3. Derived classes extend base classes with new features.

๐Ÿ”— Full Video: Inheritance in C++


Need to revisit a concept? Jump directly to the video sections with the timestamped links above! ๐Ÿš€