3

IClass (My interface):

#ifndef _ICLASS_H
#define _ICLASS_H

#include <sstream>

namespace Test
{
    class __declspec(dllexport) IClass
    {
    public:     
        virtual ~IClass() {}                

        virtual bool Init(const std::string &path) = 0;     
    };
}

#endif

Class.h

#ifndef _CLASS_H
#define _CLASS_H

#include "IClass.h"
#include <memory>
#include <sstream>
#include <stdio.h>

namespace Test
{
    class Class: public IClass
    {
    public:
        Class();
        ~Class();               

        bool Init(const std::string &path);         
    };
}

#endif

Class.cpp

#include "Class.h"

namespace Test
{
    Class::Class()
    {       
    }

    bool Class::Init(const std::string &path)
    {
        try
        {
            // do stuff

            return true;
        }
        catch(std::exception &exp)
        {
            return false;
        }
    }   
}

main (in exe, dll linked implicitly)

#include "IClass.h"

using namespace Test;

int main(int argc, char* argv[])
{
    std::shared_ptr<IClass> test = std::make_shared<Class>(); // error: unreferenced Class

    test->Init(std::string("C:\\Temp"));
}

At the moment Class is not declared

-> if I include Class.h to main following error occurs: LNK2019: unresolved external symbol: add class __declspec(dllexport) Class : public IClass resolve this linker issue, but is it ok to do it this way?

-> I also can't do this: std::shared_ptr<IClass> test = std::make_shared<IClass>(); (because it's not allowed to create an object of abstract class)

How can I solve this issue and is this best practise?

leon22
  • 5,280
  • 19
  • 62
  • 100
  • 1
    possible duplicate of [How to export a C++ class from a dll?](http://stackoverflow.com/questions/6840576/how-to-export-a-c-class-from-a-dll) – Iłya Bursov Oct 15 '13 at 23:11
  • The program will compile and work if you export (and import) Class, and include the relevant headers. Impossible to say whether or not this is good practise since you did not state your goals or constraints. – David Heffernan Oct 16 '13 at 08:33
  • @DavidHeffernan: See edit of my post – leon22 Oct 16 '13 at 11:08
  • I still do not know your goals or your constraints. – David Heffernan Oct 16 '13 at 11:09
  • @leon22 we must know if you WANT to mask the implementation details of "Class" to its users. I you do, see my answer: use a factory function. If you do not, exporting Class is fine. – manuell Oct 16 '13 at 13:25
  • @manuell I want to mask it. So thx manuell – leon22 Oct 17 '13 at 14:15

1 Answers1

2

If you want your EXE to allocate a new "Class" object, the EXE code has to know the Class type. If you want to keep the Class type unknown from the EXE, one solution may be to export from your DLL a factory function, which will construct a Class object and return it as an IClass pointer.

See How to implement the factory pattern in C++ correctly

Community
  • 1
  • 1
manuell
  • 7,528
  • 5
  • 31
  • 58