Lemme explain my problem by giving an example:
#include <iostream>
class PC
{
public:
PC():Data(0)
{
}
virtual void display()
{
std::cout<<"The data is :"<<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 is (in bb):"<<a<<std::endl;
}
};
int main()
{
SmartPC SmrtPC;
PC* miniPC= static_cast<PC*>(&SmrtPC);
SmrtPC.convert();
}
According to Scott Meyers : static_cast<PC*>(this); will create a temp base copy of SmartPC. But temp->display(); executed the display() function of derived class. Why is that so? Shouldn’t it execute the function of base’s display(), since the object is now completely a copy of base of SmartPC?
Another question is that if I add the line temp->data; in convert() function , it says
PC::Data is protected but I am accessing it from derived class scope i.e SmartPC, so why doesn’t it work?
Any help is appreciated.
No copy is created, you are only casting a pointer.
Since the class is polymorphic, calling a
virtualfunction via a pointer results in calling the “correct” version of the function (according to the dynamic type of the object, which isSmartPC *).If, instead,
displaywas notvirtual, the version of the base class would have been called, since for nonvirtualmethods it’s the static type of the pointer to determine which version is to be called.(
displayisvirtualalso inSmartPCeven if it’s not explicitly specified, thevirtualqualifier is implied when overriding inheritedvirtualfunctions)Notice instead that if you did:
you would have actually created a copy of the current object, “sliced” to be an object of type
PC. This is called “object slicing” and is performed by the copy constructor ofPC; most often this is undesired behavior (because what was an object of the derived class actually becomes an object of the base class, and polymorphism do not work as some may expect).Conceptually, when you try to access
temp->datayou’re trying to access aprivatemember of another object (it’s not important thattempis actuallythis), so the access is denied. Your “derived class privileges” to accessprotectedmembers work only onthis.