Logo 
Search:

C++ Programming FAQ

Submit Interview FAQ
Home » Interview FAQ » C++ ProgrammingRSS Feeds

C++ programming practical question 3

  Shared By: Adah Miller    Date: Jan 24    Category: C++ Programming    Views: 75

Answer:

class base
{
public:
int bval;
base(){ bval=0;}
};

class deri:public base
{
public:
int dval;
deri(){ dval=1;}
};
void SomeFunc(base *arr,int size)
{
for(int i=0; i<size; i++,arr++)
cout<<arr->bval;
cout<<endl;
}

int main()
{
base BaseArr[5];
SomeFunc(BaseArr,5);
deri DeriArr[5];
SomeFunc(DeriArr,5);
}


Answer:
00000
01010


Explanation:
The function SomeFunc expects two arguments.The first one is a pointer to an array of base class objects and the second one is the sizeof the array.The first call of someFunc calls it with an array of bae objects, so it works correctly and prints the bval of all the objects. When Somefunc is called the second time the argument passed is the pointeer to an array of derived class objects and not the array of base class objects. But that is what the function expects to be sent. So the derived class pointer is promoted to base class pointer and the address is sent to the function. SomeFunc() knows nothing about this and just treats the pointer as an array of base class objects. So when arr++ is met, the size of base class object is taken into consideration and is incremented by sizeof(int) bytes for bval (the deri class objects have bval and dval as members and so is of size >= sizeof(int)+sizeof(int) ).

Share: 
 

Didn't find what you were looking for? Find more on C++ programming practical question 3 Or get search suggestion and latest updates.


Your Comment
  • Comment should be atleast 30 Characters.
  • Please put code inside [Code] your code [/Code].


Tagged: