c++ - Virtual function acting weird in inheritance? -
lemme explain problem giving example:
#include <iostream> class pc { public: pc():data(0) { } virtual void display() { std::cout<<"the data :"<<data<<std::endl; } protected: int data; }; class smartpc:private pc { public: smartpc():pc() { } void convert() { pc* temp=static_cast<pc*>(this); temp->display(); } void display() { std::cout<<"the data (in bb):"<<a<<std::endl; } }; int main() { smartpc smrtpc; pc* minipc= static_cast<pc*>(&smrtpc); smrtpc.convert(); }
according scott meyers : static_cast<pc*>(this);
create temp base copy of smartpc. temp->display();
executed display()
function of derived class. why so? shouldn't execute function of base's display()
, since object copy of base of smartpc?
another question if add line temp->data;
in convert()
function , says pc::data
protected accessing derived class scope i.e smartpc
, why doesn't work?
any appreciated.
according scott meyers :
static_cast<pc*>(this);
create temp base copy of smartpc.temp->display();
executeddisplay()
function of derived class why so? should execute function of base'sdisplay()
, since object copy of base of smartpc.
no copy created, casting a pointer.
since class polymorphic, calling virtual
function via pointer results in calling "correct" version of function (according dynamic type of object, smartpc *
).
if, instead, display
not virtual
, version of base class have been called, since nonvirtual
methods it's static type of pointer determine version called.
(display
virtual
in smartpc
if it's not explicitly specified, virtual
qualifier implied when overriding inherited virtual
functions)
notice instead if did:
pc temp(*this);
you have created copy of current object, "sliced" object of type pc
. called "object slicing" , performed copy constructor of pc
; undesired behavior (because object of derived class becomes object of base class, , polymorphism not work may expect).
another question if add line
temp->data;
inconvert()
function , sayspc::data
protected accessing derived class scope i.esmartpc
, why doesn't works?
conceptually, when try access temp->data
you're trying access private
member of object (it's not important temp
this
), access denied. "derived class privileges" access protected
members work on this
.
Comments
Post a Comment