InterviewSolution
Saved Bookmarks
| 1. |
Can we call a virtual function from a constructor? |
|
Answer» Yes, we can call a virtual function from a constructor. But the behavior is a little different in this case. When a virtual function is called, the virtual call is RESOLVED at runtime. It is always the member function of the current CLASS that GETS called. That is the virtual MACHINE doesn’t work within the constructor. For example- class base{ private: int value; public: base(int x){ value=x; } virtual void fun(){ }}class derived{ private: int a; public: derived(int x, int y):base(x){ base *B; b=this; b->fun(); //calls derived::fun() } void fun(){ cout<<”fun inside derived class”<<endl; }} |
|