I want to make an abstract class with a pure virtual function process
.
process
should return a variable of typeResult
:
class Base {
public:
class Result {
public:
int a = 1;
virtual ~Result() {} // Virtual destructor
};
virtual Result process() = 0; // Pure abstract function
};
My idea (maybe not the right idea?) is that child classes of Base
should also re-implement Result
if they want to add information:
class Child : public Base {
public:
class ResultChild : public Base::Result {
public:
int b;
};
Base::Result process() override {
std::cout << "Processing in Child class" << std::endl;
ResultChild result;
result.a = 7;
result.b = 2;
return result;
}
};
I tried calling the chlid class as:
int main() {
Child child;
auto result = child.process(); // Does result even know the member b here?
std::cout << "a: " << result.a << std::endl; // this is 7
//std::cout << "b: " << result.b << std::endl; //‘class Base::Result’ has no member named ‘b’
// Child::ResultChild poly = dynamic_cast<Child::ResultChild>(result); // ‘class Child::ResultChild’ (target is not pointer or reference)
Child::ResultChild* poly = dynamic_cast<Child::ResultChild*>(&result); // warning: can never succeed
return 0;
}
I added the errors and warnings from my compiler in the commented code.
- Is there an actual way to make the right cast?
- Was the member
b
lost when returning? - Is this just a bad idea?
Ps. This is a simplified version of my code, in real life Base
is VideoPipeline
and forces it’s children to implement process(image)
just that some child classes may add more information than others (including types that are not available in all children classes).