is it possible to structure functions inside a class, to make some functions only accessable through a prewritten identifier?
I’ll try to make my question a litte more clear with a (poor) example 😉 My class car got the functions drive, openDoor, closeDoor, startEngine, etc. But, to keep it clear, i would like to acces these functions like this:
car.drive()
car.door.open()
car.door.close()
car.engine.start()
I tried with structs and nested classes, but i don’t think those were the right ways, because i don’t like to have to create an object for every “identifier” i use.
Are there any “clean” ways to do this?
Thanks!
Edit:
I’m not sure if it matters but heres some additional information:
- the “Car”-Class is Singelton
- apart from the functions neither the engine nor the doors or any other part of my car do have any other properties (Yay. Really poor example!)
Nested classes would be the correct approach.
Consider that all
Doorobjects would haveOpenandClosemethods, and aCarobject would have several instances of theDoorobject (2, maybe 4, or even more).Likewise, each
Carobject would have an instance of theEngineobject, which can beStarted,Stopped, and have the oil changed (ChangeOil).Then, each of these classes would be extensible beyond the
Carclass. If you wanted to change some of the code inside of yourDoorclass, all of yourCarobjects that haveDoors would automatically inherit those changes. If you wanted to swap out the engine of a car with a more powerful one, you could do that easily by passing in a new instance of theEngineobject to yourCarobject.You could use structs the same way that you would use classes, but generally you should choose to use a class rather than a struct. Structs should be reserved for types that should have value type semantics, i.e., are small, immutable, etc. For more information on the difference and how to make an informed decision, see this question.
And just in case I failed to convince you that nested classes are the correct approach, I’ll conclude by noting that they’re also the only way of achieving what you want. That is, beyond hacky solutions like appending a pseudo-namespace to the beginning of each function name (i.e.,
Car.DoorOpen), which is ugly and doesn’t really gain you anything at all.