-
Virtual Functions
Code:
#include<iostream>
using namespace std;
class A
{
public:
virtual void disp()
{
cout<<"A";
}
};
class B: public A
{
public:
void disp()
{
cout<<"B";
}
};
class C: public B
{
public:
virtual void disp()
{
cout<<"C";
}
};
int main()
{
B *a = new C();
a->disp();
getchar();
return 0;
}
here B::disp() is not virtual , so i suggest dont use dynamic binding with B class pointer containing address of any derived object.
but still output is C
i guess it has something to do with virtual A::disp() ??
-
A::disp() is virtual. B is a child of A. Therefore B::disp() is virtual too, even though it is not explicitly stated as such.
-
ok thanx
one more doubt -
Code:
#include<iostream>
using namespace std;
class A
{
};
class B: public A
{
public:
void disp()
{
cout<<"B";
}
};
int main()
{
A *a = new B();
((B *)a)->disp(); // Static Binding ??
getchar();
return 0;
}
-
Not entirely sure on this, but I would say that it is static binding, since for such a cast to be valid, a has to point to a B object, so the type of the underlying object is known at compile time.