Think Dream Create Inovate

Sunday, July 3, 2011

C++


1) class base
        {
        public:
            void baseFun(){ cout<<"from base"<
        };
 class deri:public base
        {
        public:
            void baseFun(){ cout<< "from derived"<
        };
void SomeFunc(base *baseObj)
{
        baseObj->baseFun();
}
int main()
{
base baseObject;
SomeFunc(&baseObject);
deri deriObject;
SomeFunc(&deriObject);
}
Answer:
            from base
            from base
Explanation:
            As we have seen in the previous case, SomeFunc expects a pointer to a base class. Since a pointer to a derived class object is passed, it treats the argument only as a base class pointer and the corresponding base function is called.

2) class base
        {
        public:
            virtual void baseFun(){ cout<<"from base"<
        };
 class deri:public base
        {
        public:
            void baseFun(){ cout<< "from derived"<
        };
void SomeFunc(base *baseObj)
{
        baseObj->baseFun();
}
int main()
{
base baseObject;
SomeFunc(&baseObject);
deri deriObject;
SomeFunc(&deriObject);
}
Answer:
            from base
            from derived
Explanation:
            Remember that baseFunc is a virtual function. That means that it supports run-time polymorphism. So the function corresponding to the derived class object is called.
           

No comments:

Post a Comment