© 2014 Firstsoft Technologies (P) Limited. login
Hi 'Guest'
Home SiteMap Contact Us Disclaimer
enggedu

C and C++ Interview Questions

8. What is an accessor?

Ans:

An accessor is a class operation that does not modify the state of an object. The accessor functions need to be declared as const operations

Ex 1: Which is the parameter that is added to every non-static member function when it is called?
Ans:
            ‘this’ pointer

Ex 2: Find the output of the following program
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
        cout<bval;
cout<<ENDL;
}
 
int main()
{
base BaseArr[5];
SomeFunc(BaseArr,5);
deri DeriArr[5];
SomeFunc(DeriArr,5);
}
 
Ans:
 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) ).

SLogix Student Projects
bottom