I haven’t done hard core development in C++ since I made the switch to C# about 5 years ago. I’m very familiar with using interfaces in C# and use them all the time. For example
public interface IMyInterface
{
string SomeString { get; set; }
}
public class MyClass : IMyInterface
{
public string SomeString { get; set; }
}
// This procedure is designed to operate off an interface, not a class.
void SomeProcedure(IMyInterface Param)
{
}
This is all great since you can implement lots of similar classes and pass them around, and no one is the wiser that you are actually using different classes. However, in C++ you can’t pass the interface around because you’ll get a compile error when it sees you trying to instantiate a class that does not have all its methods defined.
class IMyInterface
{
public:
...
// This pure virtual function makes this class abstract.
virtual void IMyInterface::PureVirtualFunction() = 0;
...
}
class MyClass : public IMyInterface
{
public:
...
void IMyInterface::PureVirtualFunction();
...
}
// The problem with this is that you can't declare a function like this in
// C++ since IMyInterface is not instantiateable.
void SomeProcedure(IMyInterface Param)
{
}
So what is the proper way to get the feel of C# style interfaces in C++?
Sure you can, but you need to pass references or pointers, not by value (well, pedantically speaking, pointers are passed by value as well):
I think it’s similar to C# in that regard, only that C# passes references to classes by default, whereas in C++ you explicitly have to say you want to pass it by reference.
The pass by value will attempt to create a copy of the object, and an object of an abstract type (interface) doesn’t make sense, ergo the error.