OOP: ADVANCED OOP TOPICS
Nested Classes
A nested class is a class declared inside another class.
It is useful when a helper type belongs strongly to one outer class.
Complete Example
#include <iostream>
#include <string>
using namespace std;
class University {
public:
class StudentId {
private:
string value;
public:
explicit StudentId(string idValue) : value(idValue) {}
void display() const {
cout << "Student ID: " << value << endl;
}
};
};
int main() {
University::StudentId id("CSE-101");
id.display();
return 0;
}
Output:
Student ID: CSE-101
How To Access a Nested Class
Use scope resolution:
University::StudentId
Access Rule
A nested class does not automatically get special access to a specific outer object.
It is only placed inside the scope of the outer class.
If it needs data from an outer object, that object must be passed explicitly.
Why Use Nested Classes
Use nested classes when:
- The helper class is meaningful only inside the outer class.
- You want to keep related types grouped.
- You want to avoid polluting the global namespace.
Viva Answer
A nested class is a class declared inside another class. It is accessed using the outer class scope, such as Outer::Inner. It helps group closely related helper types, but it does not automatically access data from a particular outer object.
Quick Check
- What syntax is used to access a nested class?
- Does a nested class automatically access a specific outer object?
- Why might we use a nested class?