c++ - Can members of a derived class can be accessed when its casted to base class? -
this question has answer here:
- polymorphism in c++ 9 answers
i put simple example illustrate question. here base class.
#include <mutex> #include <atomic> class task { public: task() { empty.store(true); } std::mutex access; std::atomic<bool> empty; virtual void work() = 0; };
this derived class.
#include <stdlib.h> class exampletask : public task { public: void work() { for(int = 0; < 16; ++i) { data[i] = rand(); } } private: int data[16]; };
as can see, example tasks or jobs done asynchronously. imagine, there queue of task
s , bunch of worker threads, maybe 1 each cpu core on target machine.
the task queue stores tasks casted base class, worker threads can pick next job queue , call work()
.
std::list<task*> queue; exampletask *example = new exampletask(); queue.push_back((task*)example);
a worker thread fetch first task, remove queue, , work on it.
while(true) { task *current = queue.front(); queue.erase(queue.begin()); current->work(); }
would concept work? can data
accessed when current->work()
called, if deal pointer base class?
yes: reference/pointer base class can implicitly converted pointer/reference derived class. how crtp , static polymorphism works:
template<typename t> struct crtp_base { void execute() { static_cast<t*>(this)->f(); //the instance casted known derived class, , use derived class function f. } }; struct foo : public crtp_base<foo> { void f() { std::cout << "wow, compile-time resolved polymorphism!" << std::endl; } }; int main() { foo my_foo_instance; crtp_base<foo>& base_reference = my_foo_instance; base_reference.execute(); };
this prints:
wow, compile-time resolved polymorphism!
here running example.
Comments
Post a Comment