C++/constructors
Expert: vijayan - 12/3/2008
QuestionFor the following prog u get the output as:
00000
01010
I don't understand why.. Just explain me why..
class Base
{
public:
int b;
Base()
{
b=0;
}
};
class Derived:public Base
{
public:
int d;
Derived()
{
d=1;
}
};
void fn(Base *b,int size)
{
for(int i=0;i<size;i++,b++)
cout<<b->b;
cout<<endl;
}
int main()
{
Base b[5];
fn(b,5);
Derived d[5];
fn(d,5);
}
Answerthis is a serious technical blunder.
class Base
{
// ...
};
class Derived:public Base
{
// ...
};
void fn(Base *b,int size)
{
// ...
};
int main()
{
Base b[5];
fn(b,5);
Derived d[5];
fn(d,5); // *** error *** trying to treat array of Derived as if it is an array of Base
}
sizeof(Derived) is not equal to sizeof(Base). in array
Derived d[5];
Derived* ptrd = d ;
Base* ptrb = d ;
ptrd++ ;
ptrb++ ;
for ptrd, pointer arithmetic take place in steps of sizeof(Derived).
ie. ptrd++ increments the address by sizeof(Derived).
with ptrb which is a pointer to Base, pointer arithmetic take place in steps of sizeof(Base).
ie. ptrb++ increments the address by sizeof(Base), and the result of such an increment is undefined.
the simple fact is treating an array of Derived class objects as if it is an array of Base class objects is a beginner's mistake; array subscript and pointer arithmetic will not be performed correctly.
moral of the story: do not use value semantics on object-oriented types. the consequences will be unpleasant.