Reputation: 6595
I have 2 Classes deriving from the same API, and want to be able to use the same API for both of them the only difference between the two is a define I need to put outside the API which will determine a something in the results returned by the joint function.
I'm having an issue with my design, I inherit this API and I can't change it.
Source.cpp
#include <fstream>
#include <vector>
#include "Version100.h"
#include "Version200.h"
int main()
{
Version100* ver100 = new Version100();
int res = ver100->PlusOne(2);
Version200* ver200 = new Version200();
res = ver200->PlusOne(2);
}
VersionAPI.h - this is the API I inherit I can't change this implementation
#pragma once
class VersionAPI
{
public:
VersionAPI(void);
~VersionAPI(void);
int PlusOne(int number);
};
VersionAPI.cpp - the problem I have is that I need to use different VERSION define for every class
#include "VersionAPI.h"
VersionAPI::VersionAPI(void)
{
}
VersionAPI::~VersionAPI(void)
{
}
int VersionAPI::PlusOne(int number)
{
return number + VERSION;
}
Version100.h
#pragma once
#define VERSION 100
#include "VersionAPI.h"
class Version100 :
public VersionAPI
{
public:
Version100(void);
~Version100(void);
};
Version100.cpp
#include "Version100.h"
Version100::Version100(void)
{
}
Version100::~Version100(void)
{
}
Version200.h
#pragma once
#define VERSION 200
#include "versionapi.h"
class Version200 :
public VersionAPI
{
public:
Version200(void);
~Version200(void);
};
Version200.cpp
#include "Version200.h"
Version200::Version200(void)
{
}
Version200::~Version200(void)
{
}
The error I'm getting is:
ersionapi.cpp(16): error C2065: 'VERSION' : undeclared identifier
I know this if because VERSION is defined outside the class.
Upvotes: 0
Views: 93
Reputation: 227418
You can keep the public part of the API intact, and add a private
virtual function that returns the version. The version itself can be a static
member, which is different for each derived type, or just a value returned from the version()
virtual function:
class VersionAPI
{
public:
VersionAPI();
virtual ~VersionAPI(); // Don't forget the virtual derstuctor!!!
int PlusOne(int number) const // mark "final" in C++11
{
return version() + number;
}
private:
virtual int version() const { return 123; }
};
Then implement version() const
in the derived types, returning the relevant version number.
class Version200 : public VersionAPI
{
public:
Version200();
~Version200();
private:
virtual int version() const { return 200; }
};
Upvotes: 1
Reputation: 4929
Define the VERSION
as a member of each derived class and in the VersionApi
make the PlusOne
method virtual
.
Upvotes: 1