I have examined a few posts but nothing seemed to cover my question.
I have an interface full of pure virtuals.
I have an implementation class of the interface which is made up from various public base classes.
Even though the methods are available at the implementation class the error says the virtuals are not implemented.
Remove the interface from the implementation and it is perfect.
Why aren't the implementation methods linked through to the interface?
Here is the code...
class FunctionalClass1 {
public:
int result1(int _r) {
return 1;
}
int result2(int _r) {
return 2;
}
};
class FunctionalClass2 {
public:
int result3(int _r) {
return 3;
}
int result4(int _r) {
return 4;
}
};
class MyInterface {
public:
virtual int result1(int _r) = 0;
virtual int result2(int _r) = 0;
virtual int result3(int _r) = 0;
virtual int result4(int _r) = 0;
};
class ImplementationClass1 : public FunctionalClass1, public FunctionalClass2 {
};
class ImplementationClass2 : public FunctionalClass1, public FunctionalClass2, public MyInterface {
};
ImplementationClass1* ic1 = new ImplementationClass1(); // perfect, has all the methods available
ImplementationClass2* ic2 = new ImplementationClass2(); // fails because interface not implemented
1>X:\VisualStudioRepository\...\Main.cpp(37,57): error C2259: 'ImplementationClass2': cannot instantiate abstract class
1>X:\VisualStudioRepository\...\mainclass.h(33,7): message : see declaration of 'ImplementationClass2'
1>X:\VisualStudioRepository\...\Main.cpp(37,57): message : due to following members:
1>X:\VisualStudioRepository\...\Main.cpp(37,57): message : 'int MyInterface::result1(int)': is abstract
1>X:\VisualStudioRepository\...\mainclass.h(24,14): message : see declaration of 'MyInterface::result1'
1>X:\VisualStudioRepository\...\Main.cpp(37,57): message : 'int MyInterface::result2(int)': is abstract
1>X:\VisualStudioRepository\...\mainclass.h(25,14): message : see declaration of 'MyInterface::result2'
1>X:\VisualStudioRepository\...\Main.cpp(37,57): message : 'int MyInterface::result3(int)': is abstract
1>X:\VisualStudioRepository\...\mainclass.h(26,14): message : see declaration of 'MyInterface::result3'
1>X:\VisualStudioRepository\...\Main.cpp(37,57): message : 'int MyInterface::result4(int)': is abstract
1>X:\VisualStudioRepository\...\mainclass.h(27,14): message : see declaration of 'MyInterface::result4'
I do not understand by public methods of the implementation class are not linked through to the interface. It would be nice if someone could explain why it fails. It would be great if someone could provide a solution.
Many Thanks :)
One way to achieve what you want would be to have FunciontalClass1 and FunctionalClass2 implement MyInterface:
class FunctionalClass1 : public virtual MyInterface {
public:
int result1(int _r) override {
return 1;
}
int result2(int _r) override {
return 2;
}
};
class FunctionalClass2 : public virtual MyInterface{
public:
int result3(int _r) override {
return 3;
}
int result4(int _r) override {
return 4;
}
};
class ImplementationClass2 : public FunctionalClass1, public FunctionalClass2 {
};
Note that these classes will now be abstract because they have un-implemented virtual methods. Also MyInterface needs to be virtually inherited so that ImplementationClass2 only gets a single MyInterface parent.
Another option is to provide overrides in ImplementationClass2 that delegate to FunctionalClass1 and FunctionalClass2:
class ImplementationClass2 : public FunctionalClass1, public FunctionalClass2, public MyInterface {
public:
int result1(int _r) override {
return FunctionalClass1::result1(_r);
}
int result2(int _r) override {
return FunctionalClass1::result2(_r);
}
int result3(int _r) override {
return FunctionalClass2::result3(_r);
}
int result4(int _r) override {
return FunctionalClass2::result4(_r);
}
};
Related
class Base
{
public:
static int GetType_S()
{
return 1;
}
virtual int GetType()
{
return GetType_S();
}
};
class Son1 : public Base
{
public:
static int GetType_S()
{
return 2;
}
virtual int GetType()
{
return GetType_S();
}
};
My Question is : When I need some other classes like "Son1,Son2..." ,every class should implement GetType and GetType_S function, This two functions is repeated.So How to design this classes gracefully to let son classes implement only one function?And It is best not to use macros.
You can have a class template that each SonN inherits from, which in turn inherits Base.
template <int Type>
class Middle : public Base
{
public:
static int GetType_S()
{
return Type;
}
virtual int GetType()
{
return GetType_S();
}
};
class Son1 : public Middle<2> {};
class Son2 : public Middle<3> {};
class Whatever : public Middle<42> {};
Or, if there is nothing else in those classes:
using Son1 = Middle<2>;
using Son2 = Middle<3>;
using Whatever = Middle<42>;
I'm currently trying to wrap my head around the basics of C++ inheritance. Consider the following piece of code:
// Interfaces
class InterfaceBase
{
public:
virtual void SomeMethod() = 0;
};
class InterfaceInherited : public InterfaceBase
{
};
// Classes
class ClassBase : public InterfaceBase
{
public:
virtual void SomeMethod()
{
}
};
class ClassInherited : public ClassBase, public InterfaceInherited
{
};
int main()
{
ClassBase myBase; // OK
ClassInherited myInherited; // Error on this line
return 0;
}
Here I have two interfaces with an inheritance relationship. The same goes for the two classes which implement the interfaces.
This gives me the following compiler error:
C2259 'ClassInherited': cannot instantiate abstract class
It seems that the class ClassInherited does not inherit the implementation of SomeMethod from ClassBase. Thus it is abstract and cannot be instantiated.
How would I need to modify this simple example in order to let ClassInherited inherit all the implemented methods from ClassBase?
You are encountering a diamond problem.
The solution is to use virtual inheritance (Live), to ensure that only one copy of base class members are inherited by grand-childs:
// Interfaces
class InterfaceBase
{
public:
virtual void SomeMethod() = 0;
};
class InterfaceInherited : virtual public InterfaceBase
{
};
// Classes
class ClassBase : virtual public InterfaceBase
{
public:
virtual void SomeMethod()
{
}
};
class ClassInherited : public ClassBase, public InterfaceInherited
{
};
int main()
{
ClassBase myBase; // OK
ClassInherited myInherited; // OK
return 0;
}
class Base{
protected:
int remainItems = 0;
public:
Base(){}
virtual int numOfItem() = 0;
};
class Deveried1 : public Base{
public:
Deveried1() :Base(){ remainItems = numOfItem(); }
int numOfItem(){
return 5;
}
};
class Deveried2 : public Base{
public:
Deveried2() :Base(){ remainItems = numOfItem(); }
int numOfItem(){
return 10;
}
};
class Deveried3 : public Base{
public:
Deveried3() :Base(){ remainItems = numOfItem(); }
int numOfItem(){
return 10;
}
};
int main(){
Base* foo = new Deveried3;
}
With this design, for every deveried class, I must do the same thing in constructor to initalize remainItems. I'd like to know if there are some better way/pattern in this situation.
Indeed, you can't call derived class functions from the base class constructor, so this kind of twisted inversion of dependencies can't work. I'd pass the value to the base-class constructor:
Base(int numOfItems) : remainItems(nomOfItems) {}
Derived1() : Base(5) {}
Derived2() : Base(10) {}
I do not see any benefit in the method, so I removed it and added an option to pass the variable in the base class constructor:
class Base{
protected:
int remainItems;
public:
Base(remainItems = 0) { this->remainItems = remainItems; }
};
class Deveried1 : public Base{
public:
Deveried1() :Base(5){}
}
};
class Deveried2 : public Base{
public:
Deveried2() :Base(10){}
}
};
class Deveried3 : public Base{
public:
Deveried3() :Base(10){}
}
};
int main(){
Base* foo = new Deveried3;
}
I believe what you're looking for is called the Non-Virtual Interface pattern.
How to implement an interface class using the non-virtual interface idiom in C++?
I'm getting a compile error when I try to compile my code.
The error is this:
multi.cc: In function ‘int main()’:
multi.cc:35: error: cannot declare variable ‘mdc’ to be of abstract type ‘MostDerivedClass’
multi.cc:27: note: because the following virtual functions are pure within ‘MostDerivedClass’:
multi.cc:13: note: virtual int Interface2::common_func()
multi.cc:36: error: request for member ‘common_func’ is ambiguous
multi.cc:13: error: candidates are: virtual int Interface2::common_func()
multi.cc:21: error: virtual int InterimClass::common_func()
And here is my code:
class Interface1 {
public:
virtual int common_func() = 0;
virtual ~Interface1() {};
};
class Interface2 {
public:
virtual int common_func() = 0;
virtual int new_func() = 0;
virtual ~Interface2() {};
};
class InterimClass : public Interface1 {
public:
virtual int common_func() {
return 10;
}
};
class MostDerivedClass : public InterimClass, public Interface2 {
public:
virtual int new_func() {
return 20;
}
};
int main() {
MostDerivedClass mdc;
int x = mdc.common_func();
cout << "The value = " << x << endl;
Interface2 &subset_of_funcs = dynamic_cast<Interface2 &>(mdc);
x = subset_of_funcs.common_func();
}
My questions:
How do I tell the compiler that common_func() is already implemented by the InterimClass which is a base class of MostDerivedClass?
Is there another way to fix my problem? What I would really like to do is to be able to also call common_func from Interface2. I'm working with some legacy code with a huge amount of methods in Interface1. In my new code, I only want to call a small set of these Interface1 functions, plus a few that I need to add.
You need to define a common_func() anyway in MostDerivedClass to satisfy your inheritance from Interface2
you can try something like
virtual int common_func() {
return InterimClass::common_func();
}
This is most useful if you cannot change the first Interface1
If you want a real inheritance relationship between your classes you need to follow Lol4t0 advice. Extract a superclass from Interface1, and make Interface2 subclass of this newly created class. Example :
class RootInterface{
public :
virtual int common_func() = 0;
virtual ~RootInterface(){}
};
class Interface1 : public virtual RootInterface{
public:
virtual ~Interface1() {};
};
class Interface2 : public virtual RootInterface{
public:
virtual int new_func() = 0;
virtual ~Interface2() {};
};
class InterimClass : public Interface1 {
public:
virtual int common_func() {
return 10;
}
};
class MostDerivedClass : public InterimClass, public Interface2 {
public:
virtual int new_func() {
return 20;
}
};
Add an override in MostDerivedClass, and from it call InterimClass::common_func().
First of all, I don't really understand the sense of your code.
You need to know that only Interface1::common_func is implemented.
Why don't you make Interface2 inherit from Interface1? I guess you want for both common_func methods to be equal.
Example code (uses polymorphism):
class Interface1
{
public:
virtual int common_func() = 0;
virtual ~Interface1() {};
};
class Interface2 : public Interface1 {
public:
virtual int common_func() = 0;
virtual int new_func() = 0;
virtual ~Interface2() {};
};
class InterimClass : public Interface2 {
public:
virtual int common_func() {
return 10;
}
};
class MostDerivedClass : public InterimClass {
public:
virtual int new_func() {
return 20;
}
};
int test_func()
{
Interface1 * i1 = new MostDerivedClass;
int x = i1->common_func();
cout << "The value = " << x << endl;
Interface2 * i2 = new MostDerivedClass;
x = i2->common_func();
return 0;
}
Let the second interface be derived from the first interface, remove the declaration of virtual int common_func() = 0; from the second interface, & use the keyword virtual to guide the compiler to the implementation.
class Interface1 {
public:
virtual int common_func() = 0;
virtual ~Interface1() {};
};
class BaseClass : public virtual Interface1 {
public:
virtual int common_func() {
return 10;
}
};
class Interface2 : public virtual Interface1{
public:
virtual int new_func() = 0;
virtual ~Interface2() {};
};
class DerivedClass : public virtual BaseClass, public virtual Interface2 {
public:
virtual int new_func() {
return 20;
}
};
There are two base classes have same function name. I want to inherit both of them, and over ride each method differently. How can I do that with separate declaration and definition (instead of defining in the class definition)?
#include <cstdio>
class Interface1{
public:
virtual void Name() = 0;
};
class Interface2
{
public:
virtual void Name() = 0;
};
class RealClass: public Interface1, public Interface2
{
public:
virtual void Interface1::Name()
{
printf("Interface1 OK?\n");
}
virtual void Interface2::Name()
{
printf("Interface2 OK?\n");
}
};
int main()
{
Interface1 *p = new RealClass();
p->Name();
Interface2 *q = reinterpret_cast<RealClass*>(p);
q->Name();
}
I failed to move the definition out in VC8. I found the Microsoft Specific Keyword __interface can do this job successfully, code below:
#include <cstdio>
__interface Interface1{
virtual void Name() = 0;
};
__interface Interface2
{
virtual void Name() = 0;
};
class RealClass: public Interface1,
public Interface2
{
public:
virtual void Interface1::Name();
virtual void Interface2::Name();
};
void RealClass::Interface1::Name()
{
printf("Interface1 OK?\n");
}
void RealClass::Interface2::Name()
{
printf("Interface2 OK?\n");
}
int main()
{
Interface1 *p = new RealClass();
p->Name();
Interface2 *q = reinterpret_cast<RealClass*>(p);
q->Name();
}
but is there another way to do this something more general that will work in other compilers?
This problem doesn't come up very often. The solution I'm familiar with was designed by Doug McIlroy and appears in Bjarne Stroustrup's books (presented in both Design & Evolution of C++ section 12.8 and The C++ Programming Language section 25.6). According to the discussion in Design & Evolution, there was a proposal to handle this specific case elegantly, but it was rejected because "such name clashes were unlikely to become common enough to warrant a separate language feature," and "not likely to become everyday work for novices."
Not only do you need to call Name() through pointers to base classes, you need a way to say which Name() you want when operating on the derived class. The solution adds some indirection:
class Interface1{
public:
virtual void Name() = 0;
};
class Interface2{
public:
virtual void Name() = 0;
};
class Interface1_helper : public Interface1{
public:
virtual void I1_Name() = 0;
void Name() override
{
I1_Name();
}
};
class Interface2_helper : public Interface2{
public:
virtual void I2_Name() = 0;
void Name() override
{
I2_Name();
}
};
class RealClass: public Interface1_helper, public Interface2_helper{
public:
void I1_Name() override
{
printf("Interface1 OK?\n");
}
void I2_Name() override
{
printf("Interface2 OK?\n");
}
};
int main()
{
RealClass rc;
Interface1* i1 = &rc;
Interface2* i2 = &rc;
i1->Name();
i2->Name();
rc.I1_Name();
rc.I2_Name();
}
Not pretty, but the decision was it's not needed often.
You cannot override them separately, you must override both at once:
struct Interface1 {
virtual void Name() = 0;
};
struct Interface2 {
virtual void Name() = 0;
};
struct RealClass : Interface1, Interface2 {
virtual void Name();
};
// and move it out of the class definition just like any other method:
void RealClass::Name() {
printf("Interface1 OK?\n");
printf("Interface2 OK?\n");
}
You can simulate individual overriding with intermediate base classes:
struct RealClass1 : Interface1 {
virtual void Name() {
printf("Interface1 OK?\n");
}
};
struct RealClass2 : Interface2 {
virtual void Name() {
printf("Interface2 OK?\n");
}
};
struct RealClass : RealClass1, RealClass2 {
virtual void Name() {
// you must still decide what to do here, which is likely calling both:
RealClass1::Name();
RealClass2::Name();
// or doing something else entirely
// but note: this is the function which will be called in all cases
// of *virtual dispatch* (for instances of this class), as it is the
// final overrider, the above separate definition is merely
// code-organization convenience
}
};
Additionally, you're using reinterpret_cast incorrectly, you should have:
int main() {
RealClass rc; // no need for dynamic allocation in this example
Interface1& one = rc;
one.Name();
Interface2& two = dynamic_cast<Interface2&>(one);
two.Name();
return 0;
}
And here's a rewrite with CRTP that might be what you want (or not):
template<class Derived>
struct RealClass1 : Interface1 {
#define self (*static_cast<Derived*>(this))
virtual void Name() {
printf("Interface1 for %s\n", self.name.c_str());
}
#undef self
};
template<class Derived>
struct RealClass2 : Interface2 {
#define self (*static_cast<Derived*>(this))
virtual void Name() {
printf("Interface2 for %s\n", self.name.c_str());
}
#undef self
};
struct RealClass : RealClass1<RealClass>, RealClass2<RealClass> {
std::string name;
RealClass() : name("real code would have members you need to access") {}
};
But note that here you cannot call Name on a RealClass now (with virtual dispatch, e.g. rc.Name()), you must first select a base. The self macro is an easy way to clean up CRTP casts (usually member access is much more common in the CRTP base), but it can be improved. There's a brief discussion of virtual dispatch in one of my other answers, but surely a better one around if someone has a link.
I've had to do something like this in the past, though in my case I needed to inherit from one interface twice and be able to differentiate between calls made on each of them, I used a template shim to help me...
Something like this:
template<class id>
class InterfaceHelper : public MyInterface
{
public :
virtual void Name()
{
Name(id);
}
virtual void Name(
const size_t id) = 0;
}
You then derive from InterfaceHelper twice rather than from MyInterface twice and you specify a different id for each base class. You can then hand out two interfaces independently by casting to the correct InterfaceHelper.
You could do something slightly more complex;
class InterfaceHelperBase
{
public :
virtual void Name(
const size_t id) = 0;
}
class InterfaceHelper1 : public MyInterface, protected InterfaceHelperBase
{
public :
using InterfaceHelperBase::Name;
virtual void Name()
{
Name(1);
}
}
class InterfaceHelper2 : public MyInterface, protected InterfaceHelperBase
{
public :
using InterfaceHelperBase::Name;
virtual void Name()
{
Name(2);
}
}
class MyClass : public InterfaceHelper1, public InterfaceHelper2
{
public :
virtual void Name(
const size_t id)
{
if (id == 1)
{
printf("Interface 1 OK?");
}
else if (id == 2)
{
printf("Interface 2 OK?");
}
}
}
Note that the above hasn't seen a compiler...
class BaseX
{
public:
virtual void fun()
{
cout << "BaseX::fun\n";
}
};
class BaseY
{
public:
virtual void fun()
{
cout << "BaseY::fun\n";
}
};
class DerivedX : protected BaseX
{
public:
virtual void funX()
{
BaseX::fun();
}
};
class DerivedY : protected BaseY
{
public:
virtual void funY()
{
BaseY::fun();
}
};
class DerivedXY : public DerivedX, public DerivedY
{
};
There are two other related questions asking nearly (but not completely) identical things:
Picking from inherited shared method names. If you want to have rc.name() call ic1->name() or ic2->name().
Overriding shared method names from (templated) base classes. This has simpler syntax and less code that your accepted solution, but does not allow for access to the functions from the derived class. More or less, unless you need to be able to call name_i1() from an rc, you don't need to use things like InterfaceHelper.