I am trying to create a very modular program by using interfaces. Coming from a C# background, I would use interfaces as variable types so I could use polymorphism, allowing myself/others to pass many different objects that inherit from this interface into a function/variable. However, I am getting many strange errors when trying to do this in C++. What am I doing wrong here?
I would like be able to have interface-typed variables. However, the following produces compilation errors. I think the compiler thinks my ErrorLogger class is abstract, because it inherits from an abstract class or something.
ILogger * errorLogger = ErrorLogger();
error C2440: 'initializing' : cannot convert from 'automation::ErrorLogger' to 'automation::ILogger *'
If I am going about this the wrong way, even design-wise, I am learning and will gladly listen to any and all advice.
ILogger.h:
#ifndef _ILOGGER_H_
#define _ILOGGER_H_
namespace automation
{
class ILogger
{
public:
virtual void Log(const IError &error) = 0;
};
}
#endif
ErrorLogger.h:
#ifndef _ERRORLOGGER_H_
#define _ERRORLOGGER_H_
#include "ILogger.h"
#include "IError.h"
/* Writes unhandled errors to a memory-mapped file.
*
**/
namespace automation
{
class ErrorLogger : public ILogger
{
public:
ErrorLogger(const wchar_t * file = nullptr, const FILE * stream = nullptr);
~ErrorLogger(void);
void Log(const IError &error);
};
}
#endif
ErrorLogger.cpp:
#include "stdafx.h"
#include "ErrorLogger.h"
#include "IError.h"
using namespace automation;
ErrorLogger::ErrorLogger(const wchar_t * file, const FILE * stream)
{
}
void ErrorLogger::Log(const IError &error)
{
wprintf_s(L"ILogger->ErrorLogger.Log()");
}
ErrorLogger::~ErrorLogger(void)
{
}
IError.h:
#ifndef _IERROR_H_
#define _IERROR_H_
namespace automation
{
class IError
{
public:
virtual const wchar_t *GetErrorMessage() = 0;
virtual const int &GetLineNumber() = 0;
};
}
#endif
Compilation Errors:
Thanks, -Francisco