C
chresan
Hello,
I have a question about polymorphism in c++. I have much experience in
other programming languages, but not very much in c++. I found an
unexpected behavior in following code
#include <iostream>
using namespace std;
class Abstract
{ public:
virtual void msg()=0;
void printmsg() { msg(); };
};
class Aublic Abstract
{ public: virtual void msg() { cout<<"class A"<<endl; }; };
class Bublic Abstract
{ public: virtual void msg() { cout<<"class B"<<endl; }; };
int main()
{
A a;
B b;
a.printmsg(); // prints 'class A'
b.printmsg(); // prints 'class B'
Abstract& tmp=a;
tmp.printmsg(); // prints 'class A'
tmp=b;
tmp.printmsg(); // prints 'class A' ???
return 0;
}
Ok, my question is why 'tmp', after 'b' is assigned to it, prints
'class A' instead of 'class B'. But more important: is it possible to
implement the expected behaviour ?
Thank you for any hint. And please excuse if my english is too silly.
Chresan
I have a question about polymorphism in c++. I have much experience in
other programming languages, but not very much in c++. I found an
unexpected behavior in following code
#include <iostream>
using namespace std;
class Abstract
{ public:
virtual void msg()=0;
void printmsg() { msg(); };
};
class Aublic Abstract
{ public: virtual void msg() { cout<<"class A"<<endl; }; };
class Bublic Abstract
{ public: virtual void msg() { cout<<"class B"<<endl; }; };
int main()
{
A a;
B b;
a.printmsg(); // prints 'class A'
b.printmsg(); // prints 'class B'
Abstract& tmp=a;
tmp.printmsg(); // prints 'class A'
tmp=b;
tmp.printmsg(); // prints 'class A' ???
return 0;
}
Ok, my question is why 'tmp', after 'b' is assigned to it, prints
'class A' instead of 'class B'. But more important: is it possible to
implement the expected behaviour ?
Thank you for any hint. And please excuse if my english is too silly.
Chresan