BulGali
BulGali

Reputation: 157

vector.size() returns 0 all the time

I have the following class:

class MyVector{
public:
    MyVector(int num);
    virtual ~MyVector();
    int my_size();
private:
    vector<int> some_vector;
};

The constructor and size function look like this:

MyVector::MyVector(int num) {
    vector <int> some_vector(num); 
}

int MyVector::my_size() {
    return this->some_vector.size(); 

However when running these lines:

MyVector *Bul = new MyVector(5);
    cout << Bul->my_size() << endl;

The output is 0. Can anyone explain why is this happening?

Upvotes: 2

Views: 462

Answers (1)

Cory Kramer
Cory Kramer

Reputation: 117856

Your constructor makes a local variable that shadows your member variable

MyVector::MyVector(int num) {
    vector<int> some_vector(num); 
}

Instead use the member initialization list

MyVector::MyVector(int num)
  : some_vector(num)
{
}

Upvotes: 9

Related Questions