Reputation: 157
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
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