Hi guys, I have a question about class method declaration of externally defined object... it's quite difficult to explain so here is an example of my situation:
my project is composed of some static libraries, say my_lib1..., and the executable my_app, which links the libraries.
From my_lib1 I want to call a method of a global object (MyType g_my_object) declared and defined in my_app. Generally I would have written:
1 2 3 4 5 6
//In my_lib1, where I want make the call
#include "MyTypeHeader.h"
externclass MyType g_my_object;
//...
g_my_object.MyMethod();
the problem is that MyType class is declared in my_app and I can't simply include MyTypeHeader.h class header because the class if full of elsewhere defined type attributes (and MFC specific types).
So my question is: is there any way of making a declaration of MyMethod()?
After some tries this seems to work, but I don't know why and if it is the correct approach:
1 2 3 4 5 6 7 8 9
//In my_lib1, where I want make the call
//I made a declaration of MyType specifying only the interested method, with the right signature and visibility
class MyType{
public:
void MyMethod();
};
externclass MyType g_my_object;
//...
g_my_object.MyMethod();
I'm not 100% sure I follow, so that is my disclaimer, however, if you are able to modify one of the other classes, couldn't you just wrap one in a namespace then when you need to make the calls use the resolution operator?
After all that is one of the reasons namespaces exist, to resolve ambiguity.
> After some tries this seems to work, but I don't know why and if it is the correct approach:
1 2 3 4 5 6
//In my_lib1, where I want make the call
//I made a declaration of MyType specifying only the interested method, with the right signature and visibility
class MyType{
public:
void MyMethod();
};
> the problem is that MyType class is declared in my_app and I can't simply include MyTypeHeader.h class header
> because the class if full of elsewhere defined type attributes (and MFC specific types).
You could define a helper function in my_app (in a separate header, say MyType_helper.h)
1 2
class MyType ; // opaque
void call_MyMethod( MyType& This ) ;
Implement it in the implementation file (MyType_helper.cpp) as
> So my suspects were true... I have to write such a call_MyOtherMethod for each other method I need to "export".
The other option would be to have a base class for MyType (which has no dependencies on things like MFC) where MyMethod(), MyOtherMethod() etc. are pure virtual functions. And in in my_lib1, use the base class operations polymorphically.
This is exactly what I was looking for! So I can use it as general MFC-independent interface for my object, thank you very much!
I'm not new with C++ but this is the first time I use it seriously and I still forget some C++ features like multiple inheritance :b