0

In the following code, I am creating a Vector class that inherits from the standard vector class. I am confused as to why in main, my Vector object doesn't call the derived class constructor when I include the following line

using vector<T>::vector;

but when I don't include it, it calls my derived class constructor as expected. What is the reason for this? I haven't been able to replicate the problem with toy code, so that would be very much appreciated.

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

template <class T>
class Vector : public vector<T>
{   
    vector <T> x;
    //using vector<T>::vector;
    public:
    Vector(vector <T> x)
    {
        this->x = x;
        for (auto i: this->x)
            cout << i << " ";
    }
    
};

int main() {
    Vector <int> x({1,2,3,4,5});
    return 0;
}
  • Re: "inherits from the standard vector class" -- that's generally a bad idea. `std::vector` is not designed to serve as a base class. – Pete Becker Sep 10 '21 at 12:44

1 Answers1

1

You pass {1,2,3,4,5} (which is not a std::vector) as the argument to Vector. Since std::vector provides a better match for that type, and you asked to reuse its constructors, it is constructed directly.

If you pass a std::vector<int>{1,2,3,4,5} instead, your constructor gets called.

Note also, that your example code constructs 2 std::vectors as part of Vector (the inherited one and the member x) and using namespace std is considered bad practice.

danielschemmel
  • 10,885
  • 1
  • 36
  • 58