To call correct overridden function we are supposed to pass correct pointer or reference object.
Note:- use & to pass reference variable.
For best understanding please COPY, PASTE and RUN in any online compiler.
#include <thread> #include<string> using namespace std; class Base { public: virtual void displayName(string name) { cout<<"Base :: "<<name<<endl; } }; class Derived1: public Base { public: void displayName(string name) { cout<<"Derived-1 :: "<<name<<endl; } }; class Derived2: public Base { public: void displayName(string name) { cout<<"Derived-2 :: "<<name<<endl; } }; int main() { //call overridden function using pointer Base* bPtr=nullptr; //NULL bPtr=new Derived1; std::thread objThrd(&Base::displayName,bPtr,"techSujhav.com"); objThrd.join(); delete bPtr; bPtr=new Derived2; std::thread objThrd1(&Base::displayName,bPtr,"techSujhav.com"); objThrd1.join(); delete bPtr; bPtr=new Base; std::thread objThrd2(&Base::displayName,bPtr,"techSujhav.com"); objThrd2.join(); delete bPtr; //call overridden function using refernece object Derived1 d1_Obj; Base& refBaseObj=d1_Obj; std::thread objThrd3(&Base::displayName,&refBaseObj,"refBaseObj :: techSujhav.com"); objThrd3.join(); return 0; } |
$ g++ overRide.cpp -o overRide –lpthread |
$ ./overRide Derived-1 :: techSujhav.com Derived-2 :: techSujhav.com Base :: techSujhav.com Derived-1 :: refBaseObj :: techSujhav.com |
PREV::How to call static function, member function by reference,
value and pointer in thread.
So feel free to put Questions
Your Comments /Suggestions & Questions are always welcome.
We would like to help you with best of our knowledge.
So feel free to put Questions
No comments:
Post a Comment