Skip to main content
1 of 2
nreh
  • 161
  • 8

C++ Is it okay to use nested classes as a way to namespace derived classes?

I have many abstract classes that describe many abstract ideas and objects. These classes have many complex relationships with each other, and I realize that while writing code with some of the derived classes can get confusing. For example, it isn't completely clear at first glance if class C is derived from class A, or if it derives from class B.

This is just an example and doesn't relate to the actual application:

These four classes describe 4 different types of vehicles,

  • Ground

  • Air

  • Water

  • Space

Now I'm hoping to declaring my derived classes inside the base class so I can specify the class by doing this:

class Ground {
    class HondaAccord;
}

// Now I know that HondaAccord is for certain a ground vehicle
Ground::HondaAccord car();

While for something as simple as this it's not really worth the increased clutter, In my opinion it makes it clearer and explicit in my specific codebase. Plus I could define the derived classes here and defining the functions elsewhere so I wouldn't need to import a HondaAccord.h or anything when using the HondaAccord class.

It is my understanding that the nested class is effectively the same as a normal class. I was hoping to get more information from more experienced people to understand if there are potential issues down the line that I'm not seeing.

Thanks

nreh
  • 161
  • 8