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_specifierdictates 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
publicin the derived class. - Protected members of the base class remain
protectedin 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
privatemembers of the derived class. - Protected members of the base class become
privatemembers 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).
- Public Inheritance (
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 ofPerson.public: string name;— Stores the name of the person; accessible publicly from any scope wherePersonis 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 << " Enter your Address: "; - Captures user input into the private member:
cin >> addr;
- Outputs the prompt:
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 ascout << "Addr:" << addr << endl;)
- Outputs the name field:
Derived Class Specification (
class Student : private Person):- Inheritance Mode:
private Person. - Data Members:
private: string program;— Specific toStudent, storing the academic degree program.- Member Access Transformations:
name(originallypublicinPerson) becomes aprivatemember ofStudent.setDetails()(originallypublicinPerson) becomes aprivatemember function ofStudent.printDetails()(originallypublicinPerson) becomes aprivatemember function ofStudent.addr(originallyprivateinPerson) remains inaccessible toStudentdirectly; it can only be manipulated or read viaPerson's own member functions (setDetails()andprintDetails()).- 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 becausesetDetails()is a member ofStudent(though private to external scopes). - Prompts for program data:
cout << " Enter your Program: "; - Reads data into member:
cin >> program;
- Internally invokes
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;
- Outputs header:
- Inheritance Mode:
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;
}
};
```
# Client-Side Invocation and Access Restrictions in `main()`
* **Object Instantiation:**
* `Student John;` — 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
```
* **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
```
* **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;
}
```
* **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;
}
```
* 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;
}
```
* 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;
}
```
* **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;
}
```
* **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;
}
```
* *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
Markis initialized using a single string literal"Math". - This matches the single-parameter derived constructor signature:
Lecturer(string s).
- The object
- Step-by-Step Output Order:
- Implicit invocation of base default constructor:
Person()
- Console output:
text I am a Person with no name
- Implicit invocation of base default constructor:
- Execution of derived constructor body:
Lecturer(string s)withs = "Math"- Assigns
subjects = "Math" - Console output:
text I am a lecturer and I teach Math
- Assigns
- Comparison with Special Constructor Execution:
- If the object were instantiated with two arguments, e.g.,
Lecturer Mark("Mark", "Math");:
- Explicit base constructor call
Person("Mark")executes first:text I am a person and my name is Mark
- If the object were instantiated with two arguments, e.g.,
- Derived constructor body executes second:
text I ama a lecturer and I teach Math
- Demonstrates the distinct role of member initialization lists in preventing redundant or unintended default base constructor invocations.