virtual function only works on dynamic declaration? (use of new)
I tried to find an answer on google but no luck..
considering this code...
Code:
#include <iostream>
using namespace std;
class A
{
public:
A(){}
virtual void func(){cout<< "I'm A";}
};
class B : public A
{
public:
B() : A() {}
void func(){cout<<"I'm B";}
};
class XX
{
public:
A a;
XX() {}
};
class YY : public XX
{
public:
YY(){
a = B();
}
};
int main()
{
YY y = YY();
y.a.func(); //outputs I'm A
cout<<std::endl;
A* a = new B();
a->func(); //outputs I'm B
delete a;
cout<< std::endl;
A b = B();
b.func(); //outputs I'm A
system("PAUSE");
return 0;
}
does virtual function only works on dynamically allocated (objects?)? you cant actually use it on b.func()?
I'm long been working with C++ and yet it still have something that surprises me! :D
thanks!