My math library heavily uses interfaces. It works in a way that I have an interface, for example IVector, and then child classes can derive/implement it. The reason for that is that all vectors need to be able to take a dot product with another vector, and I don't want to forget it for some reason, so it's good to have it there. Those are not exactly interfaces, though. For example, the implementation for getting the magnitude of a vector is not specific to each vector struct, so I just put it in IVector. I also have a Vector namespaces that calls functions from the IVector interface, so I will also be able to do Vector::Dot(a, b), instead of a.Dot(b).
That setup works really well, but there is a big problem: The size of the structs implementing the interfaces is bigger. After doing some testing, I found out the reason for that is the pure virtual functions:
#include <iostream>
using namespace std;
#define PRINT(thing) cout << thing << endl
struct A
{
virtual void F() = 0;
};
class B final : public A
{
};
class C
{
void F()
{
}
};
class D : public C
{
};
void main()
{
PRINT(sizeof(A)); // 4
PRINT(sizeof(B)); // 4
PRINT(sizeof(C)); // 1
PRINT(sizeof(D)); // 1
cin.get();
}
What I assumed is that the cause for that is the vpointer, but I am not sure.
But even if it makes sense that it happens, why do struct sizes not get any bigger when implementing interfaces in C#? That's a test I ran (not that I get the same result with Marshal.SizeOf for Stuff, but it doesn't work with the interfaces):
using System;
using DotNetCross.Memory;
interface IStuff
{
void DoStuff();
}
interface IPlsStop : IStuff
{
void Whatevah();
}
struct Stuff : IPlsStop
{
public void DoStuff()
{
}
public void Whatevah()
{
}
}
class Program
{
static void Main(string[] args)
{
Console.WriteLine(Unsafe.SizeOf<Stuff>()); // 1
Console.WriteLine(Unsafe.SizeOf<IStuff>()); // 8
Console.WriteLine(Unsafe.SizeOf<IPlsStop>()); // 8
Console.ReadKey();
}
}
I thought interfaces were just sugar for pure abstract classes, but apparently they are not. I assume the size of the interfaces themselves is larger because they are reference types.
So why do C# interfaces not take more memory while C++ pure-virtual functions do take up more memory?
That problem causes me way too many problems, and I must fix it. The thing I want to know the most is what I can do to make C# like interfaces in C++ (so I can implement them without the class becoming larger).