Hi, I have some C++ code and I'm not sure how to properly downcast a class. I have a generic structure (called Base) and a bunch of derived classes (100+ of them) that do various things to the members of the Base class. The trouble is users of this library can create new derived classes and "register" them so their callback will be called. Ideally, their callback will be of the right type. Derived classes do not and can not have any additional members, only functions that manipulate the state of the Base class.
In the real code, I don't know for sure which (if any) derived classes can handle the data in the Base class.
Here's some sample code I have and some questions:
#include <iostream>
class Base {
public:
char buf[12];
virtualbool isOneOfThese(Base &b) { returnfalse; };
};
class Derived1 : public Base {
public:
Derived1(Base &b) : Base(b) {}
int getSum(void) {
int sum = 0;
for (int i = 0; i < sizeof(buf); i++) {
sum += buf[i];
}
return sum;
}
staticbool staticIsOneOfThese(Base &b) {
return b.buf[0] == 1;
}
bool isOneOfThese() {
return buf[0] == 1;
}
};
// ... more derived classes here
//
void func(Derived1 &d) {
std::cout << d.getSum() << std::endl;
}
int main(int argc, char *argv[]) {
// manually build a Base for testing; these come from somewhere else
Base b;
for (auto i = 0; i < sizeof(b.buf); i++) {
b.buf[i] = 1;
}
if (Derived1::staticIsOneOfThese(b)) {
func(static_cast<Derived1&>(b));
}
return 0;
}
Questions:
(1) Is it safe to use static_cast here? I just want to call some methods in Derived1 at this point of the code.
(2) How can I code this to call isOneOfThese instead of staticIsOneOfThese. Another cast?
(3) Should I instead be using a visitor pattern?
(4) I'd like to have a generic "register" function that takes the Derived class and then the Base class can call it if it meets the isOneOfThese criteria.
It seems to me like this is a misuse of inheritance. If none of the derived classes add any state, then why not simply have all the member functions of the derived classes in the base class? What are you gaining from this design?
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <cstring>
class Base {
public:
Base() {}
Base(constchar* b) {
strcpy(buf, b);
}
virtualint getSum() { return 0; }
virtualbool isOneOfThese() const { returnfalse; }
public:
char buf[12] {};
};
class Derived1 : public Base {
public:
Derived1(const Base& b) : Base(b) {}
int getSum(void) override {
int sum = 0;
for (int i = 0; i < sizeof(buf); i++) {
sum += buf[i];
}
return sum;
}
bool isOneOfThese() const override {
return buf[0] == 1;
}
};
// ... more derived classes here
//
void func(Base& b) {
std::cout << b.getSum() << std::endl;
}
int main(int argc, char* argv[]) {
// manually build a Base for testing; these come from somewhere else
Base b;
for (auto i = 0; i < sizeof(b.buf); i++) {
b.buf[i] = 1;
}
Derived1 d(b);
if (d.isOneOfThese()) {
func(d);
}
return 0;
}
I want someone to be able to define a class that has additional methods that can be called against the base object. The data in the Base class "defines" which type of object this really is, and the code may or may not have a valid subclass for this type.
seeplus, while your code works, the snag here is that I'd prefer not to create an additional object, instead just use the current object to avoid a memory copy (performance matters here).
I don't know all the Derived class instances; the base class is in a library and users will be extending it to add their own functionality.
If you are downcasting you shouldn't use static_cast, it can lead to undefined behavior if the cast can't be done. You use dynamic_cast. And that will have performance costs.
I think the problem here is that the type OP wants to apply is dependent on the state of the object, which is independent of its type. Like, there's nothing preventing Derived1::staticIsOneOfThese(b) from returning different values for the same object b at different points in the execution. Like I said, I really think inheritance is the wrong tool for this job.
OP, what exactly are you trying to do? What do you use this for?
What I'm using this for: packets come in, and I want to have people write handlers that can optionally handle the packet, with their own predefined methods.
It looks like a visitor pattern is a better choice here. In Java, this is a lot easier and I can simply reuse use the existing object, with <? extends Base> generics. It actually is an "inheritance" issue -- the Base class has a lot of useful methods that should be callable from the instance of the subclass.
I'll have some real code and post it on github at some point so you can see what i came up with. Thanks for the pointers everyone (no pun intended)!
I really wish the callback function end-users have to write already gets the correct subclass instead of having to call a constructor, but it's still not terrible.