Best way to "redefine" a std class

N

Nafai

Hello I want to define a class myList, which is the same that std::list
except from:
- insert (I want to redefine it)
- elements can only be consulted or deleted but not modified.
- I want

Which is the best way to do that?:

1.
template <typename T> myList : public list<T> {
public:
insert(...) { ... }
...
// what about iterators?
};

OR

2.

template <typename T> myList {
private:
list<T> theList;
public:
// all the methos of list addapted to myList
// i.e.:
int size() {return theList.size(); }
...
// what about iterators?
};
 
M

msalters

Nafai said:
Hello I want to define a class myList, which is the same that std::list
except from:
- insert (I want to redefine it)
- elements can only be consulted or deleted but not modified.
- I want

Which is the best way to do that?:

1.
(public inheritance of std::list)
(private std::list member, i.e. wrap)

Easy, you must wrap. The std::list part must be private, otherwise
one can easily modify the list.

Consider the function foo( std::list<int>& );

Can you pass an instance of your list? No, so inheritance is out.
Regards,
Michiel Salters
 
A

adbarnet

...as for the iterators - just typedef them:

template <typename T> myList {
public:
typedef std::list<T> MyListType;
MyListType::const_iterator const_iterator;

const_iterator begin() const { return theList.begin(); }
const_iterator end() const { return theList.end(); }

private:
MyListType theList;
MyListType::iterator iterator;
iterator begin(){ return theList.begin(); }
iterator end() { return theList.end(); }
};
 
J

James Rafter

In general, C++ classes which were intended to be inherited from, have
virtual destructors. This is something the STL containers do not have
and so were not intended to serve as base classes.
 
J

James Rafter

In general, C++ classes which were intended to be inherited from, have
virtual destructors. This is something the STL containers do not have
and so were not intended to serve as base classes.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top