If I have a class in outside.h like:
class Outside
{
public:
Outside(int count);
GetCount();
}
How can I use it in framework.cpp using the extern keyword, where I need to instantiate the class and call GetCount?
Edit:
#include is not allowed.
Just to clarify. It is impossible to
externthe class:But, once you have the class available in framework.cpp, you CAN
externan object of typeOutside. You’ll need a .cpp file declaring that variable:And then you can refer to that object in another file via
extern(as long as you link in the correct object file when you compile your project):externis used to say "I KNOW a variable of this type with this name will exist when this program runs, and I want to use it." It works with variables/objects, not classes, structs, unions, typedefs, etc. It’s not much different fromstaticobjects.You may be thinking about forward declaring classes to cut down on compile times, but there are restrictions on that (you only get to use the objects as opaque pointers and are not able to call methods on them).
You may also mean to hide the implementation of
Outsidefrom users. In order to do that, you’re going to want to read up on the PIMPL pattern.Update
One possibility would be to add a free function to Outside.h (I’ve also added a namespace):
Implement that function in a .cpp file. While you’re at it, you might as well make the global variable that you intend to
extern(note, the variable itself does not need to be a pointer):And then do this in your program (note that you cannot call any methods on
outsidebecause you did not include outside.h and you don’t want to violate the one definition rule by adding a new definition of the class or those methods; but since the definitions are unavailable you’ll need to pass pointers tooutsidearound and notoutsideitself):I consider this an abomination, to put it mildly. Your program will find the
GetOutsideCountfunction, call it by passing it anOutside*.Outside::GetCountis actually compiled to a normal function that takes a secretOutsideobject (insideOutside::GetCountthat object is referred to via thethispointer), soGetOutsideCountwill find that function, and tell it to dereference theOutside*that was passed toGetOutsideCount. I think that’s called "going the long way ’round."But it is what it is.
If you aren’t married to using the
externkeyword, you can instead go full "let’s use C++ like it’s C" mode by adding the following two functions in the same way (i.e., via forward declarations and implementing right next toint GetOUtsideCount():I’m more willing to swallow that. It’s a lot like the strategy used by the APR.