473,763 Members | 6,638 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 1833
On 6 Jul 2005 21:31:21 -0700 in comp.lang.c++, "chresan"
<ch************ ****@fastmail.f m> 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*********@gm ail.com> wrote in message
news:11******** **************@ o13g2000cwo.goo glegroups.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******@gasca d.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(a rg)
{}
void PrintMember()
{
Base::PrintMemb er();
cout << "derivedMem ber 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_alia s = d1;
d1_derived_alia s = 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_alia s = d1;
d1_derived_alia s = d3; d1_derived_alia s is nothing but d1, so above lines are same as
d1 = d3.
It will call default assignment operator of derived class, since
d1_derived_alia s 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_ali as = 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

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

Similar topics

3
2138
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 implements InterA {} public class C implements InterA {}
37
2847
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 use the instance of this base class (or its children class). How can I ensure the instance IS-A base class instance, since Python is a fully dynamic typing language? I searched and found several different ways to do this:
18
12598
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 about whether we should allow polymorphism. Our system is not embedded and does not need to be as real-time as, say, a pacemaker. But it does involve updating displays based on radar input. So a need for something close to real-time is desired...
3
3696
by: Patchwork | last post by:
Hi Everyone, Please take a look at the following (simple and fun) program: //////////////////////////////////////////////////////////////////////////// ///////////// // Monster Munch, example program #include <list>
4
2404
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 hierarchy of algebraic matrices with the addition operation. Thus, I want to have a virtual base class class Matr;
4
4429
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 reuse for various template parameters. I wonder if there exist techniques for achieving a dynamic polymorphism using the generic programming. Is this possible? If yes, can anyone show me simple examples in C++
3
1612
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 two or more derived classes that use the same base class. It allows you to write generic code that targets the base class rather than having to write specific code for each object type." And here is the example in the book:
13
14617
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 Nicolai M. Josuttis. Chapter 14.) How to implement analogue of this technique via static polymorphism? Perhaps there is special design pattern for this purpose...
18
3863
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 different objects to respond to the same request message in their own unique way" I thought that it was: "the ability of same object to respond to different messages in
7
2479
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 has nothing to do with making multiple arguments in a declaration like:
0
9387
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10148
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10002
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
8822
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7368
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5270
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5406
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3917
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2794
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.