Hello, Ninja. Do you understand object-oriented programming? If so, you would have heard about "nested class".
In this article, we will see how nested classes in C++ works with the help of examples. Whether you are a beginner in C++ or an expert, this article will help you understand how nested classes work.
Nested Class in C++,
A nested class in C++ is a class defined within another class. A nested class provides more readability and organises the code layout, which is very helpful when you have thousands of lines of code. A nested class in C++ refers to as an inner class.
We will look into their syntax to learn more about nested classes and then proceed with working examples.
In C++, a nested class declares within the scope of the parent class.
Class Parent_Class {
//Here, data and functions implement for the parent class.
class Nested_Class {
// we will set data and functions for the nested class.
};
};
In this syntax, the Parent_Class contains a nested class called Nested_Class. The nested class has access to the private and protected members of the parent class.
Examples to understand Nested Class in C++
In this section, we will understand nested classes in C++ with the help of different examples.
Example 1
In this example, we will see how nested classes access private members of the parent class.
C++
C++
#include <iostream> using namespace std;
class ParentClass { private: int data = 5; public: class NestedClass { public: void printPrivateMember(const ParentClass& parent) { cout << parent.data ; } }; };
In the above code, a class named ParentClass is defined that contains data as a private member and then in public member, we have a Nested class called NestedClass which has public access function printPrivateMember. The printPrivateMember has access to the private members of ParentClass.
In main(), we have created an object of ParentClass and ParentClass::NestedClass, respectively. Then we call printPrivateMember() to output the data value of ParentClass.
Example 2
This example shows how nested class implements complex data structures. Here we are using a Binary search tree to explain this concept.
C++
C++
class BinarySearchTreeClass { private: struct Node { int data; Node* RightChild; Node* LeftChild; }; Node* root; public: // insert, delete, and search nodes functions class Iterator { public: // traverse the tree functions }; };
You can also try this code with Online C++ Compiler
The BinarySearchTreeClass class defines a nested Iterator class that can access private members of the parent class. The Iterator class provides functions to traverse the tree and operate on its nodes. Using a nested class like Iterator can provide a clean and encapsulated way to define specific functionality for a class.
Example 3
In this example, we will see how nested classes are used for Encapsulation.
C++
C++
#include <iostream> using namespace std;
class Counter { private: int count; // private data member to store the count // Nested class to increment and decrement the count class CountManipulator { public: void increaseCounter(Counter& c) { c.count++; } void decreaseCounter(Counter& c) { c.count--; } }; public: Counter() : count(0) {} // Constructor to initialize count to 0 void increaseCount() { CountManipulator().increaseCounter(*this); // Create a temporary object of CountManipulator to increment count } void decreaseCount() { CountManipulator().decreaseCounter(*this); // Create a temporary object of CountManipulator to decrement count } int getCount() const { return count; } };
The given code defines a Counter class which contains a private data member count and nested class, i.e. CountManipulator, that provides two functions to increment and decrement count. The Counter class uses temporary objects of CountManipulator to modify count. The main function creates an instance of Counter and calls its functions to modify and print the current value of the count.
Example 4
In this example, we look into how we Implement Member Functions of a Nested Class Outside the Enclosing Class. For this, we can define it with the help of the scope resolution operator “::”.
C++
C++
#include <bits/stdc++.h> using namespace std;
class Car { public: class Engine { public: void start(); }; }; //Member function is defined outside the class scope void Car::Engine::start() { cout << " Engine Started..." << endl; } int main() { Car::Engine en; en.start(); // calling return 0; }
You can also try this code with Online C++ Compiler
In this example, we will see how can Nested Classes be Defined Outside of their Enclosing Class. We can do it by simply moving its definition outside the enclosing class declaration using the scope resolution operator “::”.
C++
C++
#include <bits/stdc++.h> using namespace std;
class Car { public: // class Engine is defined as a public member of Car class class Engine { public: void drive() { cout << "engine started .." << endl; } void check() { cout << "working .." << endl; } }; };
int main() { Car ::Engine en ; //calling member function of engine class en.drive(); return 0; }
You can also try this code with Online C++ Compiler
In this example, we will see how to expose a Nested Class as a Public Member of its Enclosing Class. We can do it by adding the “public” keyword before the nested class declaration, and then the object of the enclosing class can access the public member functions of the nested class directly.
C++
C++
#include <bis/stdc++.h> using namespace std;
class Car { public: // class Engine is defined as a public member of Car class class Engine { public: void drive(){ cout << "engine started .." << endl; } void check(){ cout << "working .." << endl; } }; };
int main() { Car ::Engine en; //calling member function of engine class en.drive(); return 0; }
You can also try this code with Online C++ Compiler
In this example, we will see how to Expose a Nested Class as a Private Member of its Enclosing Class. We can add the “private” keyword before the nested class declaration. Since the Engine class is private, it cannot be accessed outside the Car like before.
C++
C++
#include <iostream> using namespace std;
class Car { private: class Engine { public: void start() { cout << "Engine started.\n"; } }; Engine engine; public: void drive() { engine.start(); cout << "Driving...\n"; } };
int main() { Car myCar; myCar.drive(); return 0; }
You can also try this code with Online C++ Compiler
So now, we shall discuss some important features of the Nested Class:
Encapsulation: Nested classes encapsulate the functionality and data within a class, preventing them from accessing outside the class to reduce complexity and improve code structure
Information Hiding: A nested class allow controlling the visibility of class members by making them private or protected member and showing only the public members
Improved Code Structure: improves code structure and readability by organising related functionality into nested classes
Reusability of Code: Nested classes help create reusable components for other classes or programs
Frequently Asked Questions
Q1. What is nested classes in C++?
In C++, nested classes refer to classes that are defined within the scope of another class. They are used to encapsulate related functionality or data within a parent class, enhancing code organization and access control.
Q2. What do you mean by nested classes?
"Nested classes" in C++ are classes declared inside the scope of another class. They allow for better organization of code by encapsulating related functionality within a parent class, and they can access private members of the enclosing class.
Q3. How nested class is created in C++?
To create a nested class in C++, simply declare a class within the scope of another class. The inner class has access to the members of the outer class, including private members.
Conclusion
This article discusses the Nested Class In C++ syntax and features. A nested class is a class defined in another class, which provides us with the power of encapsulation and information hiding and, at the same time, makes our code more readable and efficient.
Also, check out some of the Guided Paths on topics such as Data Structure and Algorithms, Competitive Programming, Operating Systems,Computer Networks, DBMS, System Design, etc., as well as some Contests, Test Series, Interview Bundles, and some Interview Experiences curated by top Industry Experts only on Coding Ninjas Studio.
We hope you found this blog helpful in expanding your knowledge. Please give this article a thumbs up if you enjoyed it.