2

I have a header file(let's call it Window.h) that somewhat looks like this:

#include <windows.h>

class Window {
    Window();
    HWND hwnd;
}

To use this class in another file(for example Main.cpp), Window.h has to be included:

#include "Window.h"

The problem is that I don't want Main.cpp to include windows.h, since windows.h adds a lot of macros and new declarations outside of a namespace that I don't want to be in Main.cpp. I can't move windows.h to the implementation(Window.cpp) of Window.h, since the class has the HWND attribute.

The only workaround I could think about is to declare hwnd as a pointer:

void* hwnd;

But I don't like this approach. Things might get really messy if you do this a lot. Is there a better way to do this, maybe somehow "removing" declarations and macros from the Main.cpp file?

Jannis
  • 233
  • 1
  • 7

1 Answers1

5

No, you can`t "remove" declarations, but you can hide it in two ways: 1.Impl-Pimpl idiom

//.h file
class Window {
   class Impl;
   Impl* pImpl;
   Window();
   ~Window();
   void doSomething();
};


//.cpp file
#include <windows.h>

struct Window::Impl
{
   HWND hwnd;
};

Window::Window()
{
   pImpl = new Window::Impl;
}

Window::~Window()
{
   delete pImpl;
}

void Window::doSomething()
{
   //foo(pImpl->hwnd);
}

2.Abstract class.

//.h file
class Window
{
public:
   static Window* newWindow();
   virtual void doSomething() = 0;
   virtual ~Window() {};
};

//.cpp file
#include <windows.h>

class WindowImpl : public Window
{
   HWND hwnd;
   void Window::doSomething() override
   {
      //foo(pImpl->hwnd);
   }
};


Window* Window::newWindow()
{
   return new WindowImpl();
}
Dmytro Dadyka
  • 2,208
  • 5
  • 18
  • 31