I'm doing a little experiment to try to mimic java's interfaces in C++.
I have a class "Derived" inheriting from base class "Base" and also two interfaces. I notice that with each interface I inherit from, the size of my Derived class goes up, because it has to add more space for each vptr. This seems very expensive to me, so I have two main questions:
- Is there a better way to mimic Java's interfaces in C++?
- Does Java's object size go up with every interface implemented?
Here's the code I'm using:
#include <iostream>
class Base {
public:
int derp;
virtual int getHerp() = 0;
virtual ~Base() { }
};
class Interface1 {
public:
virtual int getFlippy() = 0;
virtual ~Interface1() { }
};
class Interface2 {
public:
virtual int getSpiky() = 0;
virtual ~Interface2() { }
};
class Derived : public Base, public Interface1, public Interface2 {
public:
int herp;
virtual int getHerp() { return herp; }
virtual int getFlippy() { return 6; }
virtual int getSpiky() { return 7; }
};
int main() {
Derived d;
std::cout << sizeof(d) << std::endl;
// prints 40. presumably, Derived/Base vptr + derp + Interface1vptr + Interface2 vptr + herp
}