I have been using C++ for a long time now, but this just blows my mind. For my example I made two classes: A and B. Class A was meant to be the interface, where B is a child of A that contains the actual commands. In hope that I could use polymorphism besides the scope of an argument into a function/method, I went ahead and tried shoving and instance B into A.
I was not sure that this would work in the first place which is why I did this test. But that is not the full purpose of this post. What really blew my mind was the output (of the non-pointer version)! It returned 1! But my mind is trying to connivence itself that the outputs should either be an error or to return 5.
The pointer method works just as expected. But I would very much rather use the non-pointer method if at all possible.
Thanks for any help!Code:#include <iostream> using namespace std; class A { public: virtual int yay(){return 5;} }; class B : public A { public: int yay(){return 1;} }; int main (int argc, const char * argv[]) { A val = B(); cout << val.yay() << endl << endl; A *valp = new B(); cout << valp->yay() << endl << endl; return 0; }
==Short Version==
1) Whats up with the output?
2) How can I fix it?