Sorry for asking I believe a repeated question, but I can't figure out the problem here, maybe my understanding of this is not correct.
Setup
class Job {
public:
virtual bool createJob() {
return false;
}
};
class Limit {
public:
virtual bool updateLimit() {
return false;
}
};
class Base : public Job, public Limit {
private:
std::string cx;
public:
virtual ~Base() {
}
};
class DerivedJob : public Base {
protected:
std::string ax;
std::string bx;
std::vector<std::string> vx;
public:
bool createJob() override {
return true;
}
};
class DerivedLimit : public Base {
protected:
std::string ax;
std::string bx;
std::vector<std::string> vx;
public:
bool updateLimit() override {
return true;
}
};
Should work?
Base parent;
auto stat = static_cast<DerivedJob&>(base);
std::cout << "JOB: " << std::to_string(stat.createJob());
std::cout << "LIMIT: " << std::to_string(stat.updateLimit());
auto dyn = dynamic_cast<DerivedJob&>(base);
std::cout << "JOB: " << std::to_string(dyn.createJob());
std::cout << "LIMIT: " << std::to_string(dyn.updateLimit());
auto stat1 = static_cast<DerivedLimit&>(base);
std::cout << "JOB: " << std::to_string(stat1.createJob());
std::cout << "LIMIT: " << std::to_string(stat1.updateLimit());
auto dyn1 = dynamic_cast<DerivedLimit&>(base);
std::cout << "JOB: " << std::to_string(dyn1.createJob());
std::cout << "LIMIT: " << std::to_string(dyn1.updateLimit());
I Tried many examples and read many posts, but when I add string
and other garbage to my derived classes, it stops working, maybe my fundamental understanding of this is incorrect?
Don't be to harsh, I am only a junior in c++ :D
Thank you for your time explaining these things to me.
Additional question
How does dynamic casting work?
Example
class Device {
private:
Base _base;
public:
Device(int x) {
if (x == 5) {
DerivedJob object;
object.test = 5;
object.test2 = 1;
_base = object;
} else if (x == 7) {
DerivedLimit object;
object.test = 5;
object.test2 = 1;
_base = object;
} ...
}
}