×
>
<

C++ Programming

C++ Inheritance | CrackEase

Inheritance in C++

Inheritance in C++

Inheritance in C++ is the mechanism by which a class (called derived class) acquires properties and behaviour (data members and member functions) from another class (called base class). It is a fundamental feature of object-oriented programming that enables:

  • Code reuse
  • Faster development
  • Easier maintenance
  • Logical hierarchy and modelling of real-world relationships

Benefits of Inheritance
Benefits of inheritance

  • Reduces duplication and development cost
  • Saves time while coding
  • Decreases complexity by dividing responsibilities
  • Improves reliability by reusing tested code

Different Modes of Inheritance in C++

When deriving a class from a base class you can specify a mode (visibility) that affects how the base class members are treated in the derived class. The common modes are:

1. Public mode

  1. Public members of base remain public in derived class
  2. Protected members of base remain protected in derived class
  3. Private members of base are not accessible directly in derived class

2. Protected mode

  1. Public members of base become protected in derived class
  2. Protected members stay protected
  3. Private members remain inaccessible

3. Private mode

  1. Public members of base become private in derived class
  2. Protected members become private in derived class
  3. Private members are not accessible

Modes of inheritance
Syntax for Inheritance
  
class NameOfDerivedClass : <visibility-mode> NameOfBaseClass {
    // data members and member functions
};
  

In parent/child terms:

  
class Child : public Parent {
    // child's members
};
  
Example
  
class A {
public:
    int x;

protected:
    int y;

private:
    int z;
};

class B : public A {
    // x stays public in B
    // y stays protected in B
    // z is not accessible from B
};

class C : protected A {
    // x becomes protected in C
    // y stays protected in C
    // z is not accessible from C
};

class D : private A { // default for 'class' is private inheritance
    // x becomes private in D
    // y becomes private in D
    // z is not accessible from D
};
  
Types of inheritance in C++

Common inheritance forms include:

  • Single inheritance (one base, one derived)
  • Multilevel inheritance (chain of inheritance)
  • Multiple inheritance (derived from more than one base)
  • Hierarchical inheritance (one base, many derived)
  • Hybrid (combination of above — also called multipath)
Footer Content | CrackEase