473,473 Members | 1,754 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

Problems with objects getting sliced to base class

In the following code example I am trying to create a generic interface for a bunch of objects. Each concrete type is stored in its own container and the a container of pointer's to base is used so I can access all at once.

I created a specialization of the template for Fruit *'s so that it returns a reference and the code looks the same as when accessing a concrete type.

I've managed to get everything working so far except accessing all object in the container through a base iterator. When inserting into the base deque the objects get sliced back to the base class. And I have no idea why. I've tried various casts but none seem to work

Any help appreciated.

Adrian

#include <iostream>
#include <vector>
#include <string>
#include <deque>
#include <iterator>

class Fruit
{
public:
Fruit(const std::string &brand) : brand_(brand) {}
friend std::ostream &operator<<(std::ostream &os, const Fruit &rhs)
{
rhs.print(os);
return os;
}
virtual ~Fruit()=0;
protected:
std::string brand_;

private:
virtual void print(std::ostream &os) const
{
// should be pure - done for debug
os << "OOPS";
}
};

class Apple : public Fruit
{
public:
Apple(const std::string &brand) : Fruit(brand) {}
private:
void print(std::ostream &os) const
{
os << "I am " << brand_ << " apple";
}
};

class Pear : public Fruit
{
public:
Pear(const std::string &brand) : Fruit(brand) {}
void print(std::ostream &os) const
{
os << "I am " << brand_ << " pear";
}
};

class Orange : public Fruit
{
public:
Orange(const std::string &brand) : Fruit(brand) {}
void print(std::ostream &os) const
{
os << "I am " << brand_ << " orange";
}
};
template <class H, class T>
struct typelist
{
typedef H head;
typedef T tail;
};

class null_typelist {};

typedef typelist<Apple, typelist<Pear, typelist<Orange, null_typelist AllFruits;

template <class TList, class Tstruct IndexOf;
template<class T>
struct IndexOf<null_typelist, T>
{
enum { value=-1 };
};

template<class T, class Tail>
struct IndexOf<typelist<T, Tail>, T>
{
enum { value=0 };
};

template<class Head, class Tail, class T>
struct IndexOf<typelist<Head, Tail>, T>
{
private:
enum { temp=IndexOf<Tail, T>::value };
public:
enum { value=temp==-1?-1:1+temp };
};

Fruit::~Fruit()
{
}

class FruitBox
{
std::vector<void *containers_;
std::deque<Appleapples_;
std::deque<Pearpears_;
std::deque<Orangeoranges_;
std::deque<Fruit *fruit_;
public:
void testit(std::ostream &os)
{
for(std::deque<Fruit *>::iterator i=fruit_.begin(); i!=fruit_.end(); ++i)
{
os << *(*i) << std::endl;
}
}
FruitBox()
{
containers_.push_back(&apples_);
containers_.push_back(&pears_);
containers_.push_back(&oranges_);
}
template<class T>
class iterator : public std::iterator<std::bidirectional_iterator_tag,T,pt rdiff_t>
{
std::deque<T*r;
typename std::deque<T>::iterator it;
public:
iterator(std::deque<T&lst, const typename std::deque<T>::iterator &i)
:r(&lst), it(i) {}
bool operator==(const iterator &x) const {
return it==x.it;
}
bool operator!=(const iterator &x) const {
return !(*this==x);
}
typename std::deque<T>::reference operator*() const {
return *it;
}

iterator &operator++(){
++it;
return *this;
}
};
///////////////////////////////////////////////////////////////////////////////
template<class T>
iterator<Tbegin()
{
std::deque<T&real_cont=*reinterpret_cast<std::dequ e<T*>(containers_[IndexOf<AllFruits, T>::value]);
return iterator<T>(real_cont, real_cont.begin());
}
template<class T>
iterator<Tend()
{
std::deque<T&real_cont=*reinterpret_cast<std::dequ e<T*>(containers_[IndexOf<AllFruits, T>::value]);
return iterator<T>(real_cont, real_cont.end());
}
///////////////////////////////////////////////////////////////////////////////
template<class T>
void insert(const T &val)
{
std::deque<T&real_cont=*reinterpret_cast<std::dequ e<T*>(containers_[IndexOf<AllFruits, T>::value]);
real_cont.push_back(val);
// fruit_.push_back(const_cast<T *>(&val));
T &ptr=const_cast<T&>(val);
fruit_.push_back(&ptr);
// std::cout << "ptr=" << ptr << std::endl;
// std::cout << "val=" << val << std::endl;
testit(std::cout);
}
private:
};

template<>
class FruitBox::iterator<Fruit: public std::iterator<std::bidirectional_iterator_tag,Frui t,ptrdiff_t>
{
std::deque<Fruit **r;
std::deque<Fruit *>::iterator it;
public:
iterator(std::deque<Fruit *&lst, const std::deque<Fruit *>::iterator &i)
:r(&lst), it(i)
{
for(std::deque<Fruit *>::const_iterator woof=lst.begin(); woof!=lst.end(); ++woof)
{
std::cout << "Woof:" << *(*woof) << std::endl;
}
if(i!=lst.end())
std::cout << "iter con=" << *(*i) << std::endl;
}
bool operator==(const iterator &x) const {
return it==x.it;
}
bool operator!=(const iterator &x) const {
return !(*this==x);
}
Fruit &operator*() const
{
std::cout << "Boo:" << *(*it) << std::endl;
return **it;
}

iterator &operator++(){
++it;
return *this;
}
};

template<>
FruitBox::iterator<FruitFruitBox::begin()
{
return FruitBox::iterator<Fruit>(fruit_, fruit_.begin());
}

template<>
FruitBox::iterator<FruitFruitBox::end()
{
return FruitBox::iterator<Fruit>(fruit_, fruit_.end());
}

int main(int argc, char *argv[])
{
FruitBox box;

box.insert(Apple("Granny Smith"));
box.insert(Apple("Golden Delicious"));
box.insert(Pear("Sweet"));
box.insert(Pear("Sour"));
box.insert(Orange("Blood"));
box.insert(Orange("Navel"));

FruitBox::iterator<Appleap=box.begin<Apple>();
for(; ap!=box.end<Apple>(); ++ap)
{
std::cout << "Apple iter=" << (*ap) << std::endl;
}

FruitBox::iterator<Pearpe=box.begin<Pear>();
for(; pe!=box.end<Pear>(); ++pe)
{
std::cout << "Pear iter=" << (*pe) << std::endl;
}

FruitBox::iterator<Fruitfr=box.begin<Fruit>();
for(; fr!=box.end<Fruit>(); ++fr)
{
std::cout << "Fruit iter=" << (*fr) << std::endl;
}

//box.testit(std::cout);

return 0;
}


Jun 27 '08 #1
3 1441
>int main(int argc, char *argv[])
{
FruitBox box;

box.insert(Apple("Granny Smith"));
box.insert(Apple("Golden Delicious"));
box.insert(Pear("Sweet"));
box.insert(Pear("Sour"));
box.insert(Orange("Blood"));
box.insert(Orange("Navel"));
uhm that's because you are putting the adresses of temporary objects
into the fruits container. There is no slicing,it's undefined
behaviour.as soon as the insert() returns Apples and such cease to
exist.
Jun 27 '08 #2
hurcan solter wrote:
>int main(int argc, char *argv[])
{
FruitBox box;

box.insert(Apple("Granny Smith"));
box.insert(Apple("Golden Delicious"));
box.insert(Pear("Sweet"));
box.insert(Pear("Sour"));
box.insert(Orange("Blood"));
box.insert(Orange("Navel"));
uhm that's because you are putting the adresses of temporary objects
into the fruits container. There is no slicing,it's undefined
behaviour.as soon as the insert() returns Apples and such cease to
exist.
Excellent. Thank you.

Thats so obvious now you pointed it out.

Adrian
Jun 27 '08 #3
Adrian <bi*******@bluedreamer.comwrote in news:6
_u*****************************@comcast.com:
hurcan solter wrote:
>>int main(int argc, char *argv[])
{
FruitBox box;

box.insert(Apple("Granny Smith"));
box.insert(Apple("Golden Delicious"));
box.insert(Pear("Sweet"));
box.insert(Pear("Sour"));
box.insert(Orange("Blood"));
box.insert(Orange("Navel"));
uhm that's because you are putting the adresses of temporary objects
into the fruits container. There is no slicing,it's undefined
behaviour.as soon as the insert() returns Apples and such cease to
exist.
Excellent. Thank you.

Thats so obvious now you pointed it out.
Note that you cannot store in the fruits container also pointers to the
actual objects stored inside various other containers as the containers
may grow and the objects array be reallocated.

When working with polymorphic objects one usually uses dynamic allocation
and containers of (smart) pointers, this avoids both the slicing problem
and object moving problem. I would suggest a container of
boost::shared_ptr<Fruit>.

hth
Paavo
Jun 27 '08 #4

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

Similar topics

2
by: Michael Young | last post by:
I've been trying to compile code similar to the example code below, but I keep getting errors indicating that the function 'foo()' is not accessible. At first, I thought this was a bug in the...
1
by: Softari | last post by:
Why does program crash if object is deleted using base class pointer that is not the first base class? Please look exaple below. #include <iostream> class A { public:
5
by: Peter Hagenaar | last post by:
Hello there. I have a question about a virtual template class. The class wich derives from this class overrides a virtual method in this template base class and calls the same method in this...
4
by: Alfonso Morra | last post by:
Hi, I have a variable that stores a pointer to a base class. I am using this variable to store pointers to objects of the base class, as well as pointers to other derived classes. However,...
11
by: anongroupaccount | last post by:
What measures should be taken to avoid this sort of thing? class Base { }; class Derived1 : public Base { private: int i, j, k;
11
by: Aflj | last post by:
This code won't compile (two compilers tried, gcc and VC++, both of recent versions, but I don't remember them exactly): class C1 { public: void M1(int i) {} }; class C2: public C1
3
by: Martin Drautzburg | last post by:
For reasons related to python/swig and garbage collecting I want to remember every object in a linked list. I have a common base class RCObj which in turn has a static std::list<RCObj*memory. My...
15
by: =?Utf-8?B?R2Vvcmdl?= | last post by:
Hello everyone, I met with a strange issue that derived class function can not access base class's protected member. Do you know why? Here is the error message and code. error C2248:...
3
by: =?Utf-8?B?c29uaWNt?= | last post by:
Hi, What is the best way of populating a repeater control from a SQL Database using a base class. I am trying to impliment a base class that can be used across future websites and will populate...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
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,...
1
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,...
0
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...
0
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
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 ...
1
muto222
php
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.