You are here:

C++/constructors

Advertisement


Question
For 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);
}

Answer
this 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.  

C++

All Answers


Answers by Expert:


Ask Experts

Volunteer


vijayan

Expertise

my primary areas of interest are generic and template metaprogramming, STL, algorithms, design patterns and c++11. i would not answer questions about gui and web programming.

Experience

about 15 years or so

Education/Credentials
post graduate engineer

©2016 About.com. All rights reserved.