What I’m wondering is: if having a base class, that every* other class inherits from is a good idea or not in C++. Basically, it has the same interface as C#’s Object, which is:
*except for straight interfaces and data structures
class Object
{
public:
virtual ~Object() {}
virtual std::string toString() const = 0;
virtual Object* copy() const = 0;
virtual void release() = 0;
private:
// This operator overload calls toString() to print it out to the stream.
friend std::ostream& operator<<(std::ostream& output, const Object& object);
};
Is this a good thing to do, or am I better off just making seperate interfaces if I want the class to be copied, or converted to a string.
For example
class Copyable
{
public:
virtual ~Copyable() {}
virtual Copyable* copy() const = 0;
};
I’m not sure about this at all, and it’s doing my head in. 🙁
I wouldn’t do it. Your
Objectforces each and every class to implement those pure virtual methods. What if you don’t really need them?C++ has multiple inheritance, so you can have a separate class for each purpose, and let the derived classes decide which traits do they need.
Having those virtual function also adds an overhead, as it adds a vptr to every instance of every class. Might not have a horrible effect, but it’s not the C++ spirit IMO.
Lastely, C# and Java’s
Objecthave some useful methods because they have a lot more information on the type at runtime. This makes having a single root for all types reasonable. Some C++ frameworks have it as well (MFC’sCObjectcomes to mind), but providing useful facilities at that level is not trivial in C++. You’ll have to do more than just offer pure virtual methods – the major gain from having a single root is getting shared implementation via inheritance, not polymorphism. Using yourObjectin a polymorphic manner just breaks static typing, and in your case, you don’t even get any code reuse.