I was just doing some stuff and wrote this program. I got the following output. I know that function resolution happens at run time while binding of the variable takes place during compile time, but what I could not understand was the first output I got (this->n). Can anyone explain this to me?
# include <iostream>
# include <stdio.h>
# include <conio.h>
using namespace std;
class A
{
int n;
public:
virtual void Fun1(int no=10)
{
int n=no;
cout<<"A::Fun1() "<<n <<"\n";
}
};
class B :public A
{
int n;
public:
virtual void Fun1(int no=20)
{
int n=no;
cout<<"B::Fun1() " << this->n << "\n"; // WHY SO ? gives B::Fun1() 40
cout<<"B::Fun1() " << n << "\n";
}
};
int main()
{
B b;
A &a =b;
a.Fun1();
A a1=b;
a1.Fun1();
getch();
return 0;
}
The output I got was
B::Fun1() 40
B::Fun1() 10
A::Fun1() 10
For the first output,
this->nrefers to the member variableB::n, which you never initialise – this could print anything.For the second,
nrefers to the local variablen, which you initialise with the function argument. Since default arguments are provided by the caller, and you’re calling the function via a reference toA, you get the default value specified inA::Fun1, not the one inB::Fun1. If you were to callb.Fun1(), then it would printB::Fun1() 20.For the third, you’ve “sliced” the
Bobject, giving an object of typeA, hence the call toA::Fun1.