I have Base and Derive class at the below which related to polymorphism (Latebinding) :
class Base
{
....
};
class Derive:public Base
{
....
};
int main()
{
int n;
cin>>n;
Base *pt;
pt=new Derive[n];
for(int i=0;i<n;i++)
pt[i].Input();
}
While I was inputing the first index of pt[0]
it's fine, but in index[1]
the program is forced to close. Any idea why?
An array of Base
is not an array of Derived
. A Derived
instance can be larger than a Base
, and then address calculations go haywire when the array is treated as array of Base
. For this reason the standard specifies Undefined Behavior in this case.
Instead you can use an array of pointers to Base
.