class Base
{
int iBase;
public:
virtual void display()
{
cout<<"I am a Base Class"<<endl;
}
};
class Derived : public Base
{
int iDerived;
public:
Derived()
{
cout<<"In Derived Default Constructor"<<endl;
iDerived=10;
}
void display()
{
cout<<"I am in Derived Class"<<endl;
cout<<"value of iDerived :"<<iDerived<<endl;
iDerived=100;
cout<<"value of iDerived :"<<iDerived<<endl;
}
};
In MAIN:
Base *varBase;
Derived varDerived;
varBase = &varDerived;
varBase->display();
varBase->iDerived=10; // Error: iDerived is not a member of Base: ?????
Hi all,
I am trying to understand the Object Slicing and trying with some sample programs.
I read somewhere with the pointer reference Objcet Slicing will not happen.
But with below example I am noticing that iDerived
is not accessible from Base pointer(varBase)
, But from the virtual display method of class
I can access even though it's not in the local scope of display method.
Now my question is:
- Why I am able to access the iDerived variable only with virtual function, is this proper ?
- How to avoid object slicing.