Nested Classes

Classes can contain other structs and classes within their scope, The contained classes are called nested classes and structs. We also discuss the typedef keyword in this chapter.

Last Reviewed and Updated on February 7, 2020
Posted by Parveen(Hoven),
Aptitude Trainer and Software Developer

My C/C++ Videos on Youtube

Here is the complete playlist for video lectures and tutorials for the absolute beginners. The language has been kept simple so that anybody can easily understand them. I have avoided complex jargon in these videos.

A class within a class is called a nested class. A class is nested inside another if the inner class is a part of the outer class, and it will be used entirely by the outer class. But it is very common to see the inner classes being used independently also, so there is no hard and fast rule that the nested class has to belong to the outer class.

Example of a Nested Class

The following code shows an example of a class that holds the address information. The address has sets of related parts that can put into separate nested classes.

#include <string>
 
#include <iostream>
 
using namespace std;
 
class CLocation
{
public:
    struct CGeo
    {
        float longitude;
        float latitutude;
 
        // format is (88.7, 77.5)
        void print()
        {
            cout << "("    << longitude ;
            cout << ", "    << latitutude ;
            cout << ");"    << endl;
        }
    };
 
    struct CPost
    {
        string city;
        string pincode;
 
        void print()
        {
            cout << city << ", " << pincode;
            cout << endl;
        }
    };
 
public:
 
    void print()
    {
        m_cg.print();
        m_cp.print();
    }
 
    CGeo    m_cg;
    CPost    m_cp;
};
 
int main()
{
    CLocation loc = { {9.8f, 28.77f}, {"Kharar", "India"} };
    
    loc.print();
 
    return 0;
}

Scope Resolution and Nested Classes

If the nested class has to be accessed from outside the parent class, then scope resolution has to be done. In the example below an object of the nested class is being created inside main, and it's public function called. The nested class must be public if it has to be accessed outside the containing class.

class CA
{
public:
    class CB
    {
    public:
        void print()
        {
            cout << "hoven.in" << endl;
        }
    };
};
 
int main()
{
    CA::CB obj;
 
    obj.print();
 
    return 0;
}

Deeper nesting is also possible as can be seen in the following example. As you go deeper and deeper, the scope resolution must also reach the same depth so that the complete full path to the inner most class is written.

class CA
{
public:
    class CB
    {
    public:
        class CC
        {
        public:
            void print()
            {
                cout << "hoven.in" << endl;
            }
        };
    };
};
 
int main()
{
    CA::CB::CC obj;
 
    obj.print();
 
    return 0;
}

Access to Members of Outer Class

A nested class can access static members and enumerations of the outer class directly, i.e., without requiring a scope resolution. In the code below the nested class is able to access the static member(i) of the containing class directly, as if it were it's own. A scope resolution would be required if the nested class has a member of the same name. If no scope resolution is done, the compiler will reach the closest member, which would be its own member of the same name.

class CA
{
    static int i;
 
public:
    class CB
    {
    public:
        void print()
        {
            cout << i << endl;
        }
    };
};
 
int CA::i = 9;
 
int main()
{
    CA::CB obj;
 
    obj.print();
 
    return 0;
}

Object not Created

When a nested class is declared inside another class, then it is a declaration only; no object is created. The declaration is scoped to the containing class. By scoped, I mean that when the nested class has to be accessed from outside the containing class, then scope resolution would be required. And, when it is accessed from within the containing class, no scope resolution is required. This is similar to phone numbers that are scoped to a country. When we call each other within our country we do not have to dial the ISD number.

In the following example, no object of class CB is created. The class CB is nested inside the class CA, but the nesting alone doesn't create any objects. If any object has to be created, then the usual method of writing the class name followed by the identifier has to be used.

class CA
{
public:
    class CB
    {
    };
};

An object has to be created explicitly, like it has been done in the following code.

class CA
{
public:
    class CB
    {
    };
 
    // create a member
    // object of the nested class
    CB m_cb;
};

typedef a Nested Class

A nested class can be typedef also. What is typedef? It is a keyword of C++ that allows us to define our names for existing types. For example, if you want to give a name to "int" and call it "Marks" with the sole purpose of making your code more readable. In the following example, the int has been typedef-ed as Marks. Wherever we would have used an int, we are using "Marks". Although we are not much used to using typedefs for an int, but it can help us write a more readable code. More advanced features of C++, like the STL make use of typedef quite liberally. Here's our example for an int.

typedef int Marks;
 
int main()
{
    Marks maths = 90;
 
    cout << maths << endl;
 
    return 0;
}

On the same pattern, a nested class can be typedef-ed along with the name of the enclosing class. So when such a class would be used from outside, it can be accessed with a more readable, and neat name. The class CB has been typedef-ed below, and then it is used inside main with the new name.

class CA
{
public:
    class CB
    {
    public:
        void show()
        {
            cout << "Hello" << endl;
        }
    };
};
 
typedef CA::CB ClassB;
 
int main()
{
    ClassB obj;
 
    obj.show();
 
    return 0;
}

It is important to keep in mind that typedef of a nested class has to be done outside the class if you want to access it outside the class with the typedef-ed name. If you do the typedef inside a class, then the typedef can be used only inside that class. In the following example, the typedef of int is available only inside the scope of the class that contains it. This typedef is available to the nested classes also. It is not available for use outside the class, inside main, for example.

class CA
{
    typedef int INT;
 
public:
    class CB
    {
    public:
        void show()
        {
            INT y = 99;
            cout << y << endl;
        }
    };
};
 
int main()
{
    CA::CB obj;
 
    obj.show();
 
    // ERROR
    // INT p = 99;
 
    return 0;
}

Classroom Training

Classroom training in C/C++ is available at our training institute. Click here for details. You can also register yourself here.

Video Tutorial

We have created a video tutorial that can be downloaded and watched offline on your windows based computer. It is in the form of an exe file. No installation is required, it runs by double clicking the file. Since the exe file is hosted on the Google Drive, it should be very safe because Google itself checks for any virus or malware. The video can be watched offline, no internet is required.

Pricing

This single video will cost you USD $5. When you download the video, you will be able to watch the first few minutes for free, as a sample. The video app will prompt you for payment through PayPal and other payment options. If you want ALL VIDEOS, NOT JUST THIS ONE then go here: Complete Set of C/C++ Video Tutorials The entire set is priced at USD $50.

Screenshots

This is a screenshot of the software that should give you a good idea of the available functionality. Click on the image to see a larger view. screenshot of the video being played in the software

Installation

This software doesn't require any installation. Just download and double-click to run it. It doesn't require administrative priviliges to run. It runs in limited access mode, so should be very safe.

supports windows xp and later Supported Operating Systems

These videos can be run on 32-bit as well as 64-bit versions of the Microsoft Windows Operating Systems. Windows XP and all later OS are supported. If you want to run it on Windows XP and Windows Vista, then you must also have the .NET Framework Version 3.5 installed on your machines. Those users who have Windows 7 and later donot have to worry because these operating systems already have the .NET Framework installed on them.

Download Links

IMPORTANT NOTE: This download contains ONLY ONE video. The video is about the topic of this tutorial.

Want ALL Videos? If you want ALL VIDEOS, NOT JUST THIS ONE then go here: Complete Set of C/C++ Video Tutorials. TIP: If you plan to buy these videos, then it would be more economical to buy the entire set.

DISCLAIMER: Even though every care has been taken in making this software bug-free, but still please take a proper backup of your PC data before you use it. We shall not be responsible for any damages or consequential damages arising out of the use of this software. Please use it solely at your own risk.

Please download the software here.
download the video Nested Classes



Creative Commons License
This Blog Post/Article "Nested Classes" by Parveen (Hoven) is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.
Updated on 2020-02-07. Published on: 2015-11-20