473,327 Members | 2,090 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,327 software developers and data experts.

polymorphism question

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 A:public Abstract
{ public: virtual void msg() { cout<<"class A"<<endl; }; };
class B:public 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

Jul 23 '05 #1
10 1799
On 6 Jul 2005 21:31:21 -0700 in comp.lang.c++, "chresan"
<ch****************@fastmail.fm> wrote,
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 ?


tmp is a reference. After you create a reference, you CANNOT change
what object it is an alias for. Assigning the value of b to that
object does not change its type.

A pointer instead of a reference would be closer to what you expected.
Jul 23 '05 #2
> tmp is a reference. After you create a reference, you CANNOT change
what object it is an alias for. Assigning the value of b to that
object does not change its type.


We know that a reference cannot be reseated. But why is reseating a
reference not a compile time error? I tried that snippet with g++ 2.96
with -ansi and -Wall options. It did not give any errors or warning.
Thanks is advance.

Regards,
Srini

Jul 23 '05 #3
Yes, I tried it using pointer instead of reference and now it works.
Thank you very much
Chresan

Jul 23 '05 #4
"Srini" <sr*********@gmail.com> wrote in message
news:11**********************@o13g2000cwo.googlegr oups.com...
tmp is a reference. After you create a reference, you CANNOT change
what object it is an alias for. Assigning the value of b to that
object does not change its type.


We know that a reference cannot be reseated. But why is reseating a
reference not a compile time error?


It would be if it were possible to attempt to reseat a reference, but it
isn't. The expression in question merely assigns one object to another, with
the left side being the object to which tmp refers.

DW
Jul 23 '05 #5
Srini wrote:
tmp is a reference. After you create a reference, you CANNOT change
what object it is an alias for. Assigning the value of b to that
object does not change its type.


We know that a reference cannot be reseated. But why is reseating a
reference not a compile time error?


Because there is no syntax for doing it.

What you see as 'reseating' a reference has a very different meaning to the compiler:

A a;
B b;
Abstract& tmp=a;

tmp=b;

You read this as: reseat the reference.
The compiler reads this as: take the value of b and assign it to tmp. Now,
tmp is an alias for a, so the whole thing is equivalent to
a = b;

--
Karl Heinz Buchegger
kb******@gascad.at
Jul 23 '05 #6
"Karl Heinz Buchegger" <kb******@gascad.at> wrote in message
news:42***************@gascad.at

What you see as 'reseating' a reference has a very different meaning
to the compiler:

A a;
B b;
Abstract& tmp=a;

tmp=b;

You read this as: reseat the reference.
The compiler reads this as: take the value of b and assign it to tmp.
Now,
tmp is an alias for a, so the whole thing is equivalent to
a = b;


I am sure you know this, but for the benefit of the OP:

The fact that the reference is to the base class means that what is actually
being assigned is the base component of b to the base component of a. To
make the point clearer, let us consider a Base and Derived class, each of
which has a data member. We consider 4 different objects of the Derived
class.

If you run the following code, you will see that assignment via the Base
reference changes the data member inherited from the Base class, while not
changing the data member from the Derived class. Assignment via a Derived
reference, by contrast, changes the data member from both the Base and the
Derived class, as does direct assignment.

#include <iostream>
using namespace std;
class Base
{
int baseMember;
protected:
Base(int arg) : baseMember(arg)
{}
public:
void PrintMember()
{
cout << "baseMember is " << baseMember << ". ";
};
};

class Derived: public Base
{
int derivedMember;
public:
Derived(int arg) : Base(arg), derivedMember(arg)
{}
void PrintMember()
{
Base::PrintMember();
cout << "derivedMember is " << derivedMember << endl;
};
};

int main()
{
Derived d1(1), d2(2), d3(3), d4(4);
cout << "After construction:\n";
cout << "d1: ";
d1.PrintMember();
cout << "d2: ";
d2.PrintMember();
cout << "d3: ";
d3.PrintMember();
cout << "d4: ";
d4.PrintMember();
Base& d1_base_alias = d1;
d1_base_alias = d2;
cout << "\nAfter assignment of d2 to d1 via Base reference:\n";
cout << "d1: ";
d1.PrintMember();

Derived& d1_derived_alias = d1;
d1_derived_alias = d3;
cout << "\nAfter assignment of d3 to d1 via Derived reference:\n";
cout << "d1: ";
d1.PrintMember();

d1 = d4;
cout << "\nAfter direct assignment of d4 to d1:\n";
cout << "d1: ";
d1.PrintMember();

return 0;
}
--
John Carson

Jul 23 '05 #7
>>Base& d1_base_alias = d1;
d1_base_alias = d2; it means d1_base_alias is alias of (Base) d1 , not d1. And while
calling d1_base_alias = d2, see d1_base_alias is type of Base, not
derived, so default assingment operator of Base class will be invoked
here. So this line is equivalent to
d1_base_alias = (Base)d2;
So only members of Base class are copied.
And Since d1_base_alias is nothing but (Base)d1, so (Base) d1
datamembers are changed only.
Using pointers, we can reproduce above line as
Base *pBase = &d1;
*pBase = d2; ///See it is not pBase =&d2
Derived& d1_derived_alias = d1;
d1_derived_alias = d3; d1_derived_alias is nothing but d1, so above lines are same as
d1 = d3.
It will call default assignment operator of derived class, since
d1_derived_alias is of Derived type. so all data memebers (of base &
derived) are copied.
Using pointers we can produce same result as
Derived * pD1 = &d1;
*pD1 = d3;
d1 = d4;

This line is same as above (d1_derived_alias = d3). So result will be
same.

References are not pointers, they are only aliases.

Jul 23 '05 #8
just for a matter of interest: the C++ way of referencing objects is
pointers. There was no "reference" in the original C++. Reference was later
added to facilitate operator overloading. :)

ben
Jul 23 '05 #9


benben wrote:
just for a matter of interest: the C++ way of referencing objects is
pointers. There was no "reference" in the original C++. Reference was later
added to facilitate operator overloading. :)

ben


how did they write copy constructors without references?

Jul 23 '05 #10
"Karl Heinz Buchegger" <kb******@gascad.at> wrote in message
news:42***************@gascad.at...
Srini wrote:
tmp is a reference. After you create a reference, you CANNOT change
what object it is an alias for. Assigning the value of b to that
object does not change its type.
We know that a reference cannot be reseated. But why is reseating a
reference not a compile time error?


Because there is no syntax for doing it.

What you see as 'reseating' a reference has a very different meaning to

the compiler:
A a;
B b;
Abstract& tmp=a;

tmp=b;

You read this as: reseat the reference.
The compiler reads this as: take the value of b and assign it to tmp. Now,
tmp is an alias for a, so the whole thing is equivalent to
a = b;


Well, not quite. I nearly said this too, but a = b won't compile because the
reference is to an Abstract and 'a' is type A.

DW

Jul 23 '05 #11

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
by: Mayer Goldberg | last post by:
Can someone please explain the motivation behind the following restriction in the language: I define an interface and two classes implementing it: public interface InterA {} public class B...
37
by: Mike Meng | last post by:
hi all, I'm a newbie Python programmer with a C++ brain inside. I have a lightweight framework in which I design a base class and expect user to extend. In other part of the framework, I heavily...
18
by: Ken | last post by:
Hi. Can anyone refer me to any articles about the compatibility between c++ polymorphism and real-time programming? I'm currently on a real-time c++ project, and we're having a discussion...
3
by: Patchwork | last post by:
Hi Everyone, Please take a look at the following (simple and fun) program: //////////////////////////////////////////////////////////////////////////// ///////////// // Monster Munch, example...
4
by: Leslaw Bieniasz | last post by:
Cracow, 20.09.2004 Hello, I need to implement a library containing a hierarchy of classes together with some binary operations on objects. To fix attention, let me assume that it is a...
4
by: Leslaw Bieniasz | last post by:
Cracow, 20.10.2004 Hello, As far as I understand, the generic programming basically consists in using templates for achieving a static polymorphism of the various code fragments, and their...
3
by: John Salerno | last post by:
Along with events and delegates, polymorphism has been something I sort of struggle with every now and then. First, let me quote the book I'm reading: "Polymorphism is most useful when you have...
13
by: Krivenok Dmitry | last post by:
Hello all! Perhaps the most important feature of dynamic polymorphism is ability to handle heterogeneous collections of objects. ("C++ Templates: The Complete Guide" by David Vandevoorde and...
18
by: Seigfried | last post by:
I have to write a paper about object oriented programming and I'm doing some reading to make sure I understand it. In a book I'm reading, however, polymorphism is defined as: "the ability of two...
7
by: desktop | last post by:
This page: http://www.eptacom.net/pubblicazioni/pub_eng/mdisp.html start with the line: "Virtual functions allow polymorphism on a single argument". What does that exactly mean? I guess it...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.