C++ Inheritance, Access Specifiers, and Constructor Chaining Study Notes

Fundamentals of C++ Inheritance and Access Control

  • Core Concept of Inheritance:

    • Inheritance allows a derived class (child class) to acquire properties, data members, and member functions from a base class (parent class).
    • Standard class derivation syntax: cpp class DerivedClass : access_specifier BaseClass { // Derived class members };     
    • The access_specifier dictates the visibility and accessibility of inherited base members within the derived class and to external scopes.
  • Access Specifier Behaviors in Inheritance:

    • Public Inheritance (public):
    • Public members of the base class remain public in the derived class.
    • Protected members of the base class remain protected in the derived class.
    • Private members of the base class remain strictly inaccessible directly by the derived class.
    • Private Inheritance (private):
    • Public members of the base class become private members of the derived class.
    • Protected members of the base class become private members of the derived class.
    • Private members of the base class remain completely inaccessible directly by the derived class.
    • All inherited members become hidden from any code outside the derived class (such as the main() function).

Private Inheritance: Member Functions Accessing Private Members

  • Base Class Specification (class Person):

    • Data Members:
    • private: string addr; — Stores the address of the person; restricted entirely to the scope of Person.
    • public: string name; — Stores the name of the person; accessible publicly from any scope where Person is used directly.
    • Member Functions:
    • public: void setDetails() — Responsible for accepting input from standard input:
      • Outputs the prompt: cout << "Enter your Name:";
      • Captures user input into the string member: cin >> name;
      • Outputs the newline prompt: cout << " &nbsp;Enter your Address: ";
      • Captures user input into the private member: cin >> addr;
    • public: void printDetails() — Responsible for displaying base data to standard output:
      • Outputs the name field: cout << "Name: " << name << endl;
      • Outputs the address field: cout << "Addr: " << addr << endl; (also formatted as cout << "Addr:" << addr << endl;)
  • Derived Class Specification (class Student : private Person):

    • Inheritance Mode: private Person.
    • Data Members:
    • private: string program; — Specific to Student, storing the academic degree program.
    • Member Access Transformations:
    • name (originally public in Person) becomes a private member of Student.
    • setDetails() (originally public in Person) becomes a private member function of Student.
    • printDetails() (originally public in Person) becomes a private member function of Student.
    • addr (originally private in Person) remains inaccessible to Student directly; it can only be manipulated or read via Person's own member functions (setDetails() and printDetails()).
    • Public Interface Member Functions:
    • public: void setProgram() — Acts as a public gateway to configure both inherited base data and student-specific data:
      • Internally invokes setDetails(); — this call is legal because setDetails() is a member of Student (though private to external scopes).
      • Prompts for program data: cout << " &nbsp;Enter your Program: ";
      • Reads data into member: cin >> program;
    • public: void printProgram() — Acts as a public interface for formatted display:
      • Outputs header: cout << "STUDENT INFO" << endl;
      • Internally invokes the inherited base function: printDetails();
      • Outputs student-specific detail: cout << "Program: " << program << endl;
  • Complete Source Code Implementation:

  #include <iostream> // Inheritance: Member functions to access private members
  #include <string>
  using namespace std;

  class Person
  {
  private:
      string addr;
  public:
      string name;

      void setDetails()
      {
          cout << "Enter your Name:";
          cin >> name;
          cout << "
 Enter your Address: ";
          cin >> addr;
      }

      void printDetails()
      {
          cout << "Name: " << name << endl;
          cout << "Addr: " << addr << endl;
      }
  };

  class Student : private Person
  {
  private:
      string program;
  public:
      void setProgram()
      {
          setDetails();
          cout << "
 Enter your Program: ";
          cin >> program;
      }

      void printProgram()
      {
          cout << "STUDENT INFO" << endl;
          printDetails();
          cout << "Program: " << program << endl;
      }
  };
&nbsp;&nbsp;```

# Client-Side Invocation and Access Restrictions in `main()`

* **Object Instantiation:**
  * `Student John;` &mdash; Instantiates an object named `John` of type `Student`.
  * `John` contains both inherited members (`name`, `addr`, `setDetails()`, `printDetails()`) and its own defined members (`program`, `setProgram()`, `printProgram()`).

* **Disallowed Direct Member Access (Compile-Time Errors):**
  * Direct member assignment:
    ```cpp
    // John.name = "John Brown"; // COMPILE ERROR
&nbsp;&nbsp;&nbsp;&nbsp;```
  * **Reason:** Although `name` was originally declared `public` inside `class Person`, private inheritance (`class Student : private Person`) converts all public and protected base members into `private` members of `Student`. Consequently, `John.name` is completely inaccessible from the external scope of `main()`.
* Direct base method invocation:
    ```cpp
    // John.setDetails(); // COMPILE ERROR
&nbsp;&nbsp;&nbsp;&nbsp;```
    * **Reason:** The function `setDetails()` has become private to `Student`. The caller in `main()` is outside the class definition and cannot invoke private members.

* **Permitted Indirect Member Access (Wrapper Function Mechanism):**
  * Standard allowed function call sequence:
    ```cpp
    int main()
    {
        Student John;

        // Disallowed:
        // John.name = "John Brown";
        // John.setDetails();

        // Allowed:
        John.setProgram();
        John.printProgram();

        return 0;
    }
&nbsp;&nbsp;&nbsp;&nbsp;```
  * **Mechanism of Encapsulation:**
    * External callers interact exclusively with public member functions: `John.setProgram()` and `John.printProgram()`.
    * When `John.setProgram()` is called, it executes from inside the class scope of `Student`. Therefore, it possesses full authorization to call `setDetails()`, which in turn sets `name` and the private `addr`.
    * When `John.printProgram()` is called, it executes inside `Student` and successfully calls `printDetails()`, retrieving and printing the inherited `name` and `addr` along with `program`.

* **Curricular Attribution:**
  * Material prepared by: L. Thakur, V. T.

# Constructor Chaining and Base Class Initialization

* **Base Class Constructors (`Person`):**
  * Base class contains a public data member:
    * `public: string name;`
  * **Default Constructor:**
    ```cpp
    Person()
    {
        cout << "I am a Person with no name " << endl;
    }
&nbsp;&nbsp;&nbsp;&nbsp;```
  * Executed when a `Person` object is instantiated without arguments, or when a derived class constructor does not explicitly initialize `Person`.
* **Parameterized Constructor:**
    ```cpp
    Person(string n)
    {
        name = n;
        cout << "I am a person and my name is " << name << endl;
    }
&nbsp;&nbsp;&nbsp;&nbsp;```
    * Assigns the string parameter `n` to the member `name` and prints an informative message confirming the name.

* **Derived Class Constructors (`Lecturer : public Person`):**
  * Derived class contains public data member:
    * `public: string subjects;`
  * **Default Constructor:**
    ```cpp
    Lecturer()
    {
        cout << "I am a Lecturer with no subjects " << endl;
    }
&nbsp;&nbsp;&nbsp;&nbsp;```
  * **Execution Chain:** Automatically invokes `Person()` first, displaying `"I am a Person with no name "`, and subsequently executes its own body, displaying `"I am a Lecturer with no subjects "`.
* **Single-Parameter Constructor:**
    ```cpp
    Lecturer(string s)
    {
        subjects = s;
        cout << "I am a lecturer and I teach " << subjects << endl;
    }
&nbsp;&nbsp;&nbsp;&nbsp;```
  * **Execution Chain:** Because no explicit call to a base constructor is provided in an initialization list, C++ implicitly calls the default base constructor `Person()` first.
  * Therefore, executing this constructor causes the base default output `"I am a Person with no name "` to appear before the lecturer output `"I am a lecturer and I teach " << subjects << endl`.
* **Two-Parameter Special Constructor (Explicit Base Constructor Invocation):**
    ```cpp
    Lecturer(string n, string s) : Person(n) // Special Constructor
    {
        subjects = s;
        cout << "I ama a lecturer and I teach " << subjects << endl;
    }
&nbsp;&nbsp;&nbsp;&nbsp;```
* *Note on source text variation:* A typographical assignment `subjects = 5;` appears in compiler code drafts, but functionally represents assigning the subject string `s` to member variable `subjects`.
* **Mechanism of the Initialization List (`: Person(n)`):**
  * Bypasses the default constructor `Person()`.
  * Directly invokes the parameterized base constructor `Person(string n)` with the argument `n`.
  * Guarantees that the base class subobject is initialized with the proper name before the body of the `Lecturer` constructor runs.

# Execution Tracing: Constructor Resolution in `main()`

* **Instantiation Trace of `Lecturer Mark ("Math");`:**

cpp int main() { Lecturer Mark ("Math"); return 0; }   ```

  • Constructor Resolution Analysis:
    • The object Mark is initialized using a single string literal "Math".
    • This matches the single-parameter derived constructor signature: Lecturer(string s).
  • Step-by-Step Output Order:
    1. Implicit invocation of base default constructor: Person()
    • Console output: text I am a Person with no name &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
  1. Execution of derived constructor body: Lecturer(string s) with s = "Math"
    • Assigns subjects = "Math"
    • Console output: text I am a lecturer and I teach Math &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
  • Comparison with Special Constructor Execution:
    • If the object were instantiated with two arguments, e.g., Lecturer Mark("Mark", "Math");:
    1. Explicit base constructor call Person("Mark") executes first: text I am a person and my name is Mark &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
  1. Derived constructor body executes second: text I ama a lecturer and I teach Math &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
  • Demonstrates the distinct role of member initialization lists in preventing redundant or unintended default base constructor invocations.