Aidenhjj Aidenhjj - 1 year ago 125
C++ Question

Inheritance from Vector::Vector base class

I am trying to learn about inheritance in C++. I am trying to make a subclass of

that only takes

My grip on pointers and references is admittedly weak, but I can't for the life of me work out why the following code is setting each
to the same address:

#include <iostream>
#include <vector>
using namespace std;

class StringVector : public vector<void*> {
void push_back(const string* str) {
string* operator[](int pos) {
return (string*)vector::operator[](pos);

main() {
StringVector sv;
string str1 = "hello";
string str2 = "world";
for (int i = 0; i < 2; i++)
cout << sv[i] << " ";

When I run as is, I get:

0xffffcb68 0xffffcb68

i.e. same address.

When I try to deference the
); I get an exception. Can anyone tell me where I am going wrong?

Answer Source

You're pushing &str which takes the address of the pointer, so the type you're pushing is string**. What's more, you're storing address of a short-lived variable (pointer) - it gets destroyed as soon as you leave your overloaded push_back.

The immediate fix is to simply change the push_back method (remove const on string and pass the pointer to vector::push_back):

void push_back(string* str) {

which is as good as simply removing the method altogether and using the inherited one.

That being said, it's a bad idea to inherit from most standard containers. You can have a vector of string pointers just by typing vector<string*>.

And if you want to print the string values instead of pointers, you need to dereference them:

for (int i = 0; i < 2; i++)
    cout << *sv[i] << " ";
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download