473,662 Members | 2,704 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Templates: Come solve this puzzle....

The purpose of this puzzle is not to test your knowledge and
understanding of templates. Rather, it is to help me understand
why template based containers of entities behave differently than
template based containers of pointers to entities, specifically with
respect to dynamic binding.

The following code snippet explains what I am talking about. I have
defined a container of a base type, and in that I store instances of
the
derived type. When I invoke a virtual function, it is the base version
that gets called, not the derived version. This problem does not exist
with containers that store pointers instead.

////////////////////////////////////////////////////////////////
#include <iostream.h>
#include <list.h>

class Base
{
protected:
int i;

public:
Base(int m){ i = m;}
int get_i(){return i;}
virtual int xyz(){return i;} // Returns the value of the base
// class attribute
};

class Derived : public Base
{
protected:
int j;

public:
Derived(int m, int n):Base(m){j=n; }
int get_j(){return j;}
int xyz(){return j;} // Returns the value of the derived
// class attribute
};

typedef list<Base> BaseList;
typedef list<Base>::ite rator BaseIterator;
typedef list<Derived> DerivedList;
typedef list<Derived>:: iterator DerivedIterator ;

typedef list<Base*> BasePtrList;
typedef list<Base*>::it erator BasePtrIterator ;
typedef list<Derived*> DerivedPtrList;
typedef list<Derived*>: :iterator DerivedPtrItera tor;
main()
{
Derived *d[5];

for(int k1 = 0; k1 < 5; k1++)
{
d[k1] = new Derived(k1, 2*k1);
// The base attribute ('i') has value 0 through 4
// The derived attribute value ('j') is double
that
}

// Instance collection declarations
BaseList bcollection;
BaseIterator biter, beol;
DerivedList dcollection;
DerivedIterator diter, deol;

// Pointer collection declarations
BasePtrList bpcollection;
BasePtrIterator bpiter, bpeol;
DerivedPtrList dpcollection;
DerivedPtrItera tor dpiter, dpeol;

for(int k2 = 0; k2 < 5; k2++)
{
//Insert elements in base collection
bcollection.ins ert(bcollection .begin(), *d[k2]);

//Insert the SAME elements in the derived collection
dcollection.ins ert(dcollection .begin(), *d[k2]);

//Insert elements in base-ptr collection
bpcollection.in sert(bpcollecti on.begin(), d[k2]);

//Insert the SAME elements in the derived-ptr collection
dpcollection.in sert(dpcollecti on.begin(), d[k2]);
}

cout << "** Instance-collection behavior **\n";
// Iterate through the base collection and execute the
// virtual method "xyz()" on each element
cout << "Base collection:" << endl;
beol = bcollection.end ();
for(biter=bcoll ection.begin(); biter != beol; biter++)
cout << " get_i()=" << (*biter).get_i( ) << ", xyz()="
<< (*biter).xyz() << endl;

// Iterate through the derived collection and execute the
// virtual method "xyz()" on each element. Since we entered
// the exact same elements in both lists, the EXPECTED output
// is the same as before.
//
// Check out for yourself ;-(
//
cout << "Derived collection:" << endl;
deol = dcollection.end ();
for(diter=dcoll ection.begin(); diter != deol; diter++)
cout << " get_i()=" << (*diter).get_i( ) << ", xyz()="
<< (*diter).xyz() << endl;

cout << "The exact same elements were entered in both collections.\n"
<< "Is the output the same in both the cases?\n";

cout << "\n\n** Pointer-collection behavior **\n";
// Iterate through the base-pointer collection and execute the
// virtual method "xyz()" on each element
cout << "Base-pointer collection:" << endl;
bpeol = bpcollection.en d();
for(bpiter=bpco llection.begin( ); bpiter != bpeol; bpiter++)
cout << " get_i()=" << (*bpiter)->get_i() << ", xyz()="
<< (*bpiter)->xyz() << endl;

// Iterate through the derived-pointer collection and execute the
// virtual method "xyz()" on each element. Since we entered
// the exact same elements in both lists, the EXPECTED output
// is the same as before.
//
// No surprises this time around :-(
cout << "Derived-pointer collection:" << endl;
dpeol = dpcollection.en d();
for(dpiter=dpco llection.begin( ); dpiter != dpeol; dpiter++)
cout << " get_i()=" << (*dpiter)->get_i() << ", xyz()="
<< (*dpiter)->xyz() << endl;

cout << "The exact same elements were entered in both collections.\n"
<< "Is the output the same in both the cases?\n";
}

Jul 23 '05 #1
2 1425
kb***@kaxy.com wrote:
The purpose of this puzzle is not to test your knowledge and
understanding of templates. Rather, it is to help me understand
why template based containers of entities behave differently than
template based containers of pointers to entities, specifically with
respect to dynamic binding.
[...]


Search for "slicing" WRT classes and copying.

V
Jul 23 '05 #2
<kb***@kaxy.com > wrote in message
news:11******** **************@ z14g2000cwz.goo glegroups.com.. .
The purpose of this puzzle is not to test your knowledge and
understanding of templates. Rather, it is to help me understand
why template based containers of entities behave differently than
template based containers of pointers to entities, specifically with
respect to dynamic binding.

The following code snippet explains what I am talking about. I have
defined a container of a base type, and in that I store instances of
the
derived type. When I invoke a virtual function, it is the base version
that gets called, not the derived version. This problem does not exist
with containers that store pointers instead.


C++ !!! It slices, it dices!

Research 'slicing', and note that polymorphism in C++
requires the use of a pointer or reference to the base
class.

-Mike
Jul 23 '05 #3

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

Similar topics

4
7155
by: franky.backeljauw | last post by:
Hello, I have a problem with using a copy constructor to convert an object of a templated class to object of another templated class. Let me first include the code (my question is below): <code:templates.h> #include <string> #include <iostream>
1
2563
by: Vince C. | last post by:
Hi all, I've created XML documents that are described with a schema. I'm using those documents to create web pages. All my web pages contain a fixed header and a variable document part. The header is the same in each page and is described in an XML document, "Head.xml". The document part, which is variable in content, is described in other XML files (e.g. "Document.xml", "Product.xml", "Register.xml").
4
4777
by: ro86 | last post by:
Hello everyone! I am a newbie to C++ (~1 Week experience) and I have a few months of experience with object-oriented languages (Objective-C). I am currently working just for fun on a particle system. All the particles are controlled by a "server". The server performs all kinds of operations on them (updating, drawing etc.). The particles (my "clients") on the other hand need to retrieve once a while some information from their server...
2
1587
by: Bore Biko | last post by:
Dear, I am an ordinary C programmer and I am most interesed about dynamical data structuring and programming, I don't like to use matricess and rows, I like to program with practical programs that doesent use much memory. I know a lot of C++ programmers ,and they tolded me, that C++ templates are real solution for dynamical memory use programming.I readed 3 books about C++ , but I don't have a practice and a mass things about templates...
27
2972
by: Alf P. Steinbach | last post by:
I'm writing a little piece on pointers, to be "bundled" with my attempted correct C++ tutorial (see FAQ item 29.20, yes, I've finally started to at least think about that again), and while thinking of good examples I came up with the idea of solving the puzzle explained in code below, with the solver optimized so that a state is never analysed more than once. However, I soon realized that this could be done most naturally (for me, at...
27
2296
by: John Salerno | last post by:
Ok, here's a problem I've sort of assigned to myself for fun, but it's turning out to be quite a pain to wrap my mind around. It's from a puzzle game. It will help if you look at this image: http://www.johnjsal.devisland.net/switches.jpg Here's the situation: Each of the four rows in the diagram is considered a single 'panel'. Each panel has eight 'switches', which are composed of two columns each, and these columns have a total of 20...
1
13088
by: xavier vazquez | last post by:
I have a problem with a program that does not working properly...when the program run is suppose to generate a cross word puzzle , when the outcome show the letter of the words overlap one intop of the other....how i can fix this the program look like this import java.util.ArrayList; import java.util.Random;
1
2782
by: jimmyB | last post by:
Hi, I have one query and I hope you people can solve it. Problem is related to Smarty Caching Database Templates.. Most popular web applications and forums like IPB (invision power board) and vbulletin now a days store there all templates to database in the form of template bits (means in small portions like login form in one table row, lost password form in second row and so on). And through Admin panel if someone wants to edit then...
4
19940
by: honey777 | last post by:
Problem: 15 Puzzle This is a common puzzle with a 4x4 playing space with 15 tiles, numbered 1 through 15. One "spot" is always left blank. Here is an example of the puzzle: The goal is to get the tiles in order, 1 through 15, from left to right, top to bottom, by just sliding tiles into the empty square. In this configuration, the goal would be to get the 14 and 15 to switch places, without affecting any of the other squares. Your...
0
8857
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
8768
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...
1
8547
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8633
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
6186
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
5655
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4348
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2763
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
2
1999
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.