473,903 Members | 5,842 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Inheriting from std::vector?

BCC
Hi,

A colleague has some code like this:

class CMyObject {
// Bunch of Member functions
}

class CMyObjectList: public std::vector<CMy Object>
{
// Bunch of member functions
}

I need to inherit the functionality of his object and list as well as add
some of my own:

class CMyPersonalObje ct: public CMyObject
{
// More stuff
}

class CMyPersonalObje ctList: public CMyObjectList
{
// More stuff
}

But if I pass in CMyPersonalObje ctList to a function, and then try to assign
the CMyPersonalObje ct to a local variable of that type, I get a compiler
error telling me that I cannot convert CMyObject to CMyPersonalObje ct... the
compiler thinks the list I passed in is made of the parent objects.

What is going on and how do I fix it?

Thanks,
B
Jul 19 '05
26 10752
lilburne wrote:
You wrote bad code, having been told it's bad. What's your point?
What was bad about it?

You're destroying a non-polymorphic class object polymorphically
(through a pointer to the base class object).

But you knew that.

It's illogical to ban usage of a feature just because that feature
_can_ be abused, since almost all language features _can_ be abused,
and I think your use of such an illogical argument was the reason why
Pete plonked you.


It is unlikely that Pete Becker would derive a class from
a base that has a non-virtual destructure, without some
overriding reason to do so. Because he knows it is a
resource leak waiting to happen,


No, it's not. Polymorphically destroying an object of that class is.
A knife can be a useful tool, and it isn't evil. Hoever, using it to
stab people is. Almost everything can be destructive if you want it to
be.
and that safer alternatives are usually available.

To pretend that you can ensure that the polymorphic deletion
on such a class heirarchy can be avoid just by saying "Don't
do it" is ridiculous.
You could also reinterpret_cas t the pointer to char* and delete that
one. It will also result in improper deletion. But why would anyone do
such a stupid thing?
Certain language features ought to be used with caution, IMO
one should learn how to use them properly before you start
to abuse them.


Nope. One should learn how to use them and never abuse them at all.

Jul 19 '05 #21
Alf P. Steinbach wrote:
On Sat, 25 Oct 2003 02:55:25 +0100, lilburne <li******@godzi lla.net> wrote:

Certain language features ought to be used with caution, IMO
one should learn how to use them properly before you start
to abuse them.

Well, modest that I am I find it unlikely that either Pete or I don't
know how to use inheritance properly, and I find it unlikely that either
of us would abuse the mechanism.

Then why sanction it for others?

Perhaps you're referring to the OP?

But the OP didn't code inheritance from std::vector; he's, er, inherited
that code...
The OP was proposing deriving 3 additional class from it. If
he can't repair the initial inheritance scheme he can at
least not inherit it, or perhaps reduce the potential risk
by giving the initial inheriting class a virtual destructor.
Perhaps, then, you're referring to your own abusive example code?


The code presented isn't abusive. It simply demonstrated the
problem you are likely to have when you have an inheritance
tree whose base consists of a non virtual destructor. It
could even exist in legacy code, which the deriver is
unaware of, and whose original coder certainly wasn't
abusing the language.

Jul 19 '05 #22
Rolf Magnus wrote:
lilburne wrote:

>You wrote bad code, having been told it's bad. What's your point?
>

What was bad about it?
You're destroying a non-polymorphic class object polymorphically
(through a pointer to the base class object).

But you knew that.

It's illogical to ban usage of a feature just because that feature
_can_ be abused, since almost all language features _can_ be abused,
and I think your use of such an illogical argument was the reason why
Pete plonked you.


It is unlikely that Pete Becker would derive a class from
a base that has a non-virtual destructure, without some
overriding reason to do so. Because he knows it is a
resource leak waiting to happen,

No, it's not. Polymorphically destroying an object of that class is.
A knife can be a useful tool, and it isn't evil. Hoever, using it to
stab people is. Almost everything can be destructive if you want it to
be.


As day follows night someone will delete an object of the
class polymorphically , there may already be doing so. There
might be code in the system that deletes pointers of the
base class. They may not, nor should they, even know that
the base pointer they are dealing with is of a derived class.

In any case by inheriting from the base you are implicitly
restricting the problem space that your class can be validly
used in, and you have passed a charged on to maintainence
due to a lazy implementation. All future users of the class
have to remember not to destroy via the base, or to call any
method that might do. But you could have avoid the cost by
using composition rather than inheritance.

Jul 19 '05 #23

lilburne wrote:
[...]
In any case by inheriting from the base you are implicitly
restricting the problem space that your class can be validly
used in, and you have passed a charged on to maintainence
due to a lazy implementation. All future users of the class
have to remember not to destroy via the base, or to call any
method that might do. But you could have avoid the cost by
using composition rather than inheritance.


No thankyou.

http://google.com/groups?selm=3DF9C6...EE37E%40web.de
(Subject: Re: blocking inheritance)

regards,
alexander.
Jul 19 '05 #24
Pete Becker <pe********@acm .org> writes
>>However, as std::vector doesn't have a virtual destructor it
>>shouldn't really be being used as a base class.
>
>
> There is no problem with using it as a base class as long as you don't
> destroy the object through a pointer to std::vector.
>


And you ensure that how?


You don't do it.


I would have thought that would be quite difficult.

If you work as part of a team of developers, or for a large company
where one team expects to reuse code from another team, you'd have to
carefully document the class. Even if your fellow developers remember to
trace the chain of inheritance right back to the base class and check,
how many of them will know that std::vector doesn't have a virtual
destructor? (I didn't know until I read this thread.)

If you're a one man band, you still might post some of your code on the
internet, sell it to somebody, or be very busy and need to subcontract a
project.

Even if you know (somehow) that you will never do the above, you might
need to do a rush job and think: "OK, I can inherit from my XYZ class,
job done and dusted." Then you find yourself in the debugger at three in
the morning, drinking jolt cola or black coffee.

All the same, there are times when I would like to be able to inherit
from a std::vector or other container. I tend to typedef my STL
container declarations:

typedef std::vector<int > CsectorList;

But then I find that I can't forward declare them, because you can't
forward declare a typedef. If I could safely do:

class CsectorList:pub lic std::vector<int >{};

Then I could forward declare this as:

class CsectorList;

Anyone got any ideas for safely achieving this?
--
Simon Elliott
http://www.ctsn.co.uk/


Jul 19 '05 #25
Simon Elliott wrote:
Pete Becker <pe********@acm .org> writes
>However, as std::vector doesn't have a virtual destructor it
>shouldn' t really be being used as a base class.
There is no problem with using it as a base class as long as you don't
destroy the object through a pointer to std::vector.
And you ensure that how?
You don't do it.

I would have thought that would be quite difficult.


You know, I know it, ...

All the same, there are times when I would like to be able to inherit
from a std::vector or other container. I tend to typedef my STL
container declarations:

typedef std::vector<int > CsectorList;

But then I find that I can't forward declare them, because you can't
forward declare a typedef. If I could safely do:

class CsectorList:pub lic std::vector<int >{};

Then I could forward declare this as:

class CsectorList;

Anyone got any ideas for safely achieving this?


The question I'd ask is why you want to typedef the thing,
other than to avoid adding #include <vector>. I suppose it
might make it easier to turn it into a std::list, or
whatever, at some later stage. The problem is that you
haven't really hidden the fact that its a vector and haven't
stopped clients from using vector specific operations. I've
been there.

Another motivation I've seen is when someone inherits a
container and adds application specific operations to the
new class. The problem with this is that clients can still
treat it as a bare std::container circumventing any
application specific invariants you might want to impose.
IOW you don't protect access to the container.

Personally I'd either seperate the container specific
element from the application specific operations, or use the
has-a relationship between the classes. I prefer the later.
The result is I believe more robust over time.

Jul 19 '05 #26
lilburne <li******@godzi lla.net> writes
The question I'd ask is why you want to typedef the thing,
other than to avoid adding #include <vector>. I suppose it
might make it easier to turn it into a std::list, or
whatever, at some later stage.
There's the clarity issue as well. This is discussed quite well here:

http://www.gotw.ca/gotw/046.htm

But I'm fairly sure that you still have to #include <vector>. More
unpleasantly, if your container is a
std::vector<lar ge_nontrivial_c lass>

you also need to #include "large_nontrivi al_class.h"

So classes which didn't need to know about either std::vector or
large_nontrivia l_class still need both includes.

If we were to inherit from std::container< large_nontrivia l_class>, the
inherited class could be forward declared and neither of these includes
would be necessary.
The problem is that you
haven't really hidden the fact that its a vector and haven't
stopped clients from using vector specific operations. I've
been there.

Another motivation I've seen is when someone inherits a
container and adds application specific operations to the
new class. The problem with this is that clients can still
treat it as a bare std::container circumventing any
application specific invariants you might want to impose.
IOW you don't protect access to the container.
You could always inherit from it privately, but see below.
Personally I'd either seperate the container specific
element from the application specific operations, or use the
has-a relationship between the classes. I prefer the later.
The result is I believe more robust over time.


Yes, and this would also be safer if the container had not got a virtual
destructor. On the other hand, there may be some usefulness in exposing
the underlying container, as this allows users to apply all the generic
algorithms from the standard library to your class.
--
Simon Elliott
http://www.ctsn.co.uk/


Jul 19 '05 #27

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

Similar topics

27
6030
by: Jason Heyes | last post by:
To my understanding, std::vector does not use reference counting to avoid the overhead of copying and initialisation. Where can I get a reference counted implementation of std::vector? Thanks.
18
2896
by: Janina Kramer | last post by:
hi ng, i'm working on a multiplayer game for a variable number of players and on the client side, i'm using a std::vector<CPlayer> to store informatik about the players. CPlayer is a class that contains another std::vector<CPosition>. Because one of the players is the client itself (and the size of the vector<CPlayer> doesn't change during a game), i thought i could store a std::vector<CPlayer>::iterator "localplayer" that points to the...
20
17881
by: Anonymous | last post by:
Is there a non-brute force method of doing this? transform() looked likely but had no predefined function object. std::vector<double> src; std::vector<int> dest; std::vector<double>::size_type size = src.size(); dest.reserve(size); for (std::vector<int>::size_type i = 0;
17
3375
by: Michael Hopkins | last post by:
Hi all I want to create a std::vector that goes from 1 to n instead of 0 to n-1. The only change this will have is in loops and when the vector returns positions of elements etc. I am calling this uovec at the moment (for Unit-Offset VECtor). I want the class to respond correctly to all usage of STL containers and algorithms so that it is a transparent replacement for std:vector. The options seems to be:
8
5127
by: Ross A. Finlayson | last post by:
I'm trying to write some C code, but I want to use C++'s std::vector. Indeed, if the code is compiled as C++, I want the container to actually be std::vector, in this case of a collection of value types or std::vector<int>. So where I would use an int* and reallocate it from time to time in C, and randomly access it via , then I figure to copy the capacity and reserve methods, because I just need a growable array. I get to considering...
32
69733
by: zl2k | last post by:
hi, c++ user Suppose I constructed a large array and put it in the std::vector in a function and now I want to return it back to where the function is called. I can do like this: std::vector<int> fun(){ //build the vector v; return v; }
56
5859
by: Peter Olcott | last post by:
I am trying to refer to the same std::vector in a class by two different names, I tried a union, and I tried a reference, I can't seem to get the syntax right. Can anyone please help? Thanks
9
8902
by: aaragon | last post by:
I am trying to create a vector of type T and everything goes fine until I try to iterate over it. For some reason, the compiler gives me an error when I declare std::vector<T>::iterator iter; Any ideas why is tihs happening? The code is as follows: template <class T> struct StdVectorStorage { std::vector<T>* _storage;
13
2971
by: jubelbrus | last post by:
Hi I'm trying to do the following. #include <vector> #include <boost/thread/mutex.hpp> #include <boost/shared_ptr.hpp> #include <boost/tuple/tuple.hpp> class {
0
9999
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9847
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
10875
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
10986
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
10501
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...
0
9685
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
8049
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
6093
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
3324
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.