Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Export Parent Class Without Base Class in C++

Tags:

c++

dllexport

Given the classes Foo and Bar where Bar is derived from Foo, how could I export Bar without having to export Foo ?


Foo.h

class Foo
{
    public:
        Foo();
        virtual bool Read(...);
        virtual bool Write(...);
        ~Foo();
};


Bar.h

#ifdef BUILD_DLL
#    include "Foo.h"
#    define EXTERNAL __declspec(dllexport)
#else
#    define EXTERNAL __declspec(dllimport)
#endif 

class EXTERNAL Bar: public Foo
{
    public:
        Bar();
        bool Read(...);
        bool Write(...);
        ~Bar();
};



Edit

This is the warning that Visual C++ 2010 gives me:

warning C4275: non dll-interface class 'Foo' used as base for dll-interface class 'Bar'



Edit #2

Here's what I did to sort-of solve the issue. I made Foo and Bar separate DLL's. The client application links to Bar.dll and Bar.dll links to Foo.dll. This works well for what I was trying to achieve...

like image 370
Drew Chapin Avatar asked May 01 '26 18:05

Drew Chapin


2 Answers

Doesn't that work? It should. Just because you're not explicitly exporting the class doesn't mean the logic isn't in the binary. The symbols just aren't visible to anything importing that class.

Your solution should do it. Are you getting linking errors or what?

EDIT: I just saw you only include the header for Foo in one case. You don't need to do that:

#ifdef BUILD_DLL
#    define EXTERNAL __declspec(dllexport)
#else
#    define EXTERNAL __declspec(dllimport)
#endif 

#include "Foo.h"

class EXTERNAL Bar: public Foo
{
    public:
        Bar();
        bool Read(...);
        bool Write(...);
        ~Bar();
};

This way you can't use Foo in a different module since it's not exported, but you can use and declare Bar.

like image 85
Luchian Grigore Avatar answered May 03 '26 10:05

Luchian Grigore


Foo is needed to create a Bar instance - in fact, to create Bar, Foo's constructor is called prior to Bar's constructor.

I highly doubt you can export one and use it without exporting the other.

like image 27
John Humphreys Avatar answered May 03 '26 09:05

John Humphreys