473,396 Members | 2,009 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,396 software developers and data experts.

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>::iterator BaseIterator;
typedef list<Derived> DerivedList;
typedef list<Derived>::iterator DerivedIterator;

typedef list<Base*> BasePtrList;
typedef list<Base*>::iterator BasePtrIterator;
typedef list<Derived*> DerivedPtrList;
typedef list<Derived*>::iterator DerivedPtrIterator;
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;
DerivedPtrIterator dpiter, dpeol;

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

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

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

//Insert the SAME elements in the derived-ptr collection
dpcollection.insert(dpcollection.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=bcollection.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=dcollection.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.end();
for(bpiter=bpcollection.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.end();
for(dpiter=dpcollection.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 1410
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.googlegr oups.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
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): ...
1
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...
4
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...
2
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...
27
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...
27
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: ...
1
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...
1
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...
4
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...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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...
0
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...
0
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,...

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.