Virtual function & Inheritance issue..!!

Please consider the code snippet below..


#include <iostream>
using namespace std;

class A
{
public:
int data;

public:

A() : data(4)
{ };

virtual int getData() const
{
cout<<"Inside A::getData().. this pointer = "<<this<<endl;
return data;
}
};

class B : public A
{
public:
int data;

public:
B() : data(5)
{ };

int getData() const
{
cout<<"Inside B::getData().. this pointer = "<<this<<endl;
return data;
}
};

int main()
{
cout<<"Sizeof(A) = "<<sizeof(A)<<" ... Sizeof(B) = "<<sizeof(B)<<endl;

A* poA = new B;
cout<<"poA->getData() = "<<poA->getData()<<endl; /* Prints 5 */
cout<<"poA->data = "<<poA->data<<endl; /* Prints 4.. why?? */

delete poA;

return 0;
}

/*
Why is there a difference in output. What is the rule here..!!
poA->getData() prints 5 but poA->data prints 4..!!
*/

I think the problem is that you are declaring data twice in class B as it inherits A::data

When posting code use [code][/code] tags
1. when u use poA->getData(), getData() from derived class gets called and it returns value of data as 5 (value of B::data is used on the bases of its scope)

2. type of poA is A so when u access poA->data, A::data is used which is having value 4
Last edited on
To be clearer, the class A has a virtual method hence is a polymorphic.
Though the pointer poA is associated with class A type (for compile-time polymorphism), the virtual method in the class hierarchy would take help of virtual table or pointer to check what object exactly is pointed-to underneath and determines which getData() of (parent or overriding) is to be invoked at run-time. This is run-time polymorphism.

Coming to data, the member property is not polymorphic, meaning no virtuality is associated with it. Hence the compile-time determined data type would play the role when the member property is invoked from other caller programs. Since the compile-time type played role, the actually pointed-to object is left behind obviously.

Hope it is clear now.

Good luck :)
Topic archived. No new replies allowed.