I think this is a really newb question, but I never found out the answer. I don’t know how exactly to phrase this question, but I often find that I have to access objects that are “far away” from the current object in terms of the current hierarchy. I just want to make sure that this is the right (only) way to do this.
This goes along with passing parameters in from main also. I find that some objects far away from main need to be passed in with a parameter multiple times. How does an object far away from main get information from the command line?
For example for the first case, for 4 classes…
class A{
B b;
//need to check status of D
//choice 1
b.get_c().get_d().get_status();
//choice 2
const C& c = b.get_c();
const D& d = c.get_d();
d.get_status();
};
class B{
public:
C c;
const C& get_c() {return c;}
};
class C{
public:
D d;
const D& get_d() {return d;}
};
class D{
public:
bool check_status();
};
Say something like, A is car, B is door assembly, C is door, D is lock. Then A has to check say, is lock on, otherwise prevent starting.
Choice 3 is to directly call D’s method from A, I’d have to make a few layers of check_status() in C, B, and A and return D, C, B.check_status().
Don’t all these calls to subobjects (if the code was a bit more complicated) get a lot of overhead?
Thanks.
The answer to this sort of question is always the same: Don’t worry about it unless and until it becomes a problem, and then, take measurements to decide which option is best. Yes, there’s an overhead with calls to subobjects but with the example you’ve given (and with many real-life examples) this overhead is unavoidable (and the compiler may optimize some of it away anyway).