inherits from class vector?

Is this possible?
Yes it is possible but I don't recommend it.
Yes it is possible but I don't recommend it.


May I ask why? What if there comes a situation where you want std::vector (or std::anything really) with some extra features?

Not debating, I'm just curious what could go wrong.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#include <algorithm>
#include <initializer_list>
#include <iomanip>
#include <iostream>
#include <ostream>
#include <vector>

template <typename T>
class Vector: public std::vector<T> {
public:

	Vector(std::initializer_list<T> il):
		std::vector<T>(il)
	{
	}

	typename std::vector<T>::size_type length() const
	{
		return std::vector<T>::size();
	}

	void sort()
	{
		std::sort(std::vector<T>::begin(), std::vector<T>::end());
	}

	void printOn(std::ostream &os = std::cout) const
	{
		for (const T &t: *this)
			os << t << ' ';

		os << std::endl;
	}
};

int main()
{
	Vector<int> vi{4, -4, 6, -5, 200, 90};

	vi.printOn();
	vi.sort();
	vi.printOn();
}


Hmm. How long can you go on like this, until you start relying on the internal implementation? Look at how ugly the code looks, too. (Unless there's something I don't know.)

And finally: is your own Vector compatible with std::vector? Not unless you write an conversion constructor or a conversion operator.
Topic archived. No new replies allowed.