In the Code Below there are Two Classes. One Object of type two is created and then it is assigned to pointer of class one.
On Calling the out function, the out function of the class one is called.
#include<iostream>
using namespace std;
class one
{
public :
void out()
{
cout<<"one ";
}
};
class two
{
public :
void out()
{
cout<<"two ";
}
};
int main()
{
two dp[3];
one *bp = (one *)dp;
for (int i=0; i<3;i++)
(bp++)->out();
}
OUTPUT
one one one
Output according to me should be two instead of one.
When we created the object of type two, the memory location of that object contained the address of the function of out of class two, then why on assignment, out of class one is called ?
EDIT –
moreover even if we change the name of function in class two, the output is not changed.
It’s not uncommon for a novice to assume that all C++ member functions “belong” to an object.
As you noticed, they don’t.
Conceptually – the precise procedure is a compiler implementation detail – your
outmember functions are transformed into “free” functions that look like these:For non-member functions, that’s all that’s needed.
When the compiler sees
it knows that bp is a pointer to
one(it doesn’t know that you lied), and so it callsbecause that’s what compilers do.