Aidenhjj Aidenhjj - 1 month ago 13
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

vector::vector
that only takes
string
pointers.

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
string
to the same address:

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

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

main() {
StringVector sv;
string str1 = "hello";
string str2 = "world";
sv.push_back(&str1);
sv.push_back(&str2);
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
sv[i]
(i.e.
*sv[i]
); I get an exception. Can anyone tell me where I am going wrong?

Answer

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) {
    vector::push_back(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] << " ";