Solved Exposing class methods to other classes?
-
Howdy folks, here's an interesting one I've run into. Say you have 2 classes (class A and classB), in classA you want to access B::method(), why is this so complicated? Well, I guess it is for me as a beginner. Any ideas? I tried using classB exposeB; in my classA header but keep getting crashes about it being undefined.
classa.h #ifndef CLASSA_H #define CLASSA_H #include "classb.h" class classB; class ClassA { public: ClassA(); void getClassAIntValue(); int valueA; private: classB exposeB; }; #endif // CLASSA_H
classa.cpp #include "classa.h" #include <QDebug> ClassA::ClassA() { valueA = 15777889; exposeB.getClassBIntValue(); } void ClassA::getClassAIntValue() { qDebug() << "getClassAIntValue() reached!" << valueA; }
classb.h #ifndef CLASSB_H #define CLASSB_H #include "classa.h" class ClassA; class classB { public: classB(); void getClassBIntValue(); int valueB; private: ClassA exposeA; }; #endif // CLASSB_H
classb.cpp #include "classb.h" #include <QDebug> classB::classB() { valueB = 25777889; } void classB::getClassBIntValue() { qDebug() << "getClassBIntValue() reached!" << valueB; }
-
@Calicoder said in Exposing class methods to other classes?:
but keep getting crashes about it being undefined.
I don't think you mean "crashes". You mean "compilation errors", don't you?
Your problem here is to do with each of the two classes trying to
#include
the other class's header file. I haven't got time to type up the steps the compiler will go through with what you have, but I can see the problem.Partly your problem is because in each one you try to have an actual instance of the other one, instead of a pointer to an instance of the other one. What you have will never work:
ClassA
holds an actualClassB
instance, andClassB
holds an actualClassA
instance: if you think about it that can never be possible.If you changed where in
classa.h
you haveclassB exposeB
over toclassB *exposeB
, and the same the other way round inclassb.h
to make it haveClassA *exposeA
, you would get further. (You'd still have to make code changes because now they are pointers.)However, in general we try to keep it so that one class might include/know about the other class, but then not vice versa. Not always, but where possible. Indeed, having two much mutual referencing is how you end with spaghetti code!
So... either figure what I have said and do it with pointers (and therefore
new
-ing the instances), or for now just make it one direction: haveClassA
includeClassB
but not the other way round too, and see how you go. -
@JonB Appreciate it, thanks and a great explanation for sure.