-1

So this might be a silly question but I couldn't find any solution online.

I was reading the book "A Tour of C++" by Bjarne Stroustrup and I tried to follow Section 2.3.2. We first defined a class called Vector:

#include <iostream>

class Vector {
    public:
        Vector(int s) :elem{new double[s]}, sz{s} { } // constr uct a Vector
        double& operator[](int i) {return elem[i]; } // element access: subscripting
        int size() { return sz; }
        
    private:
        double* elem; // pointer to the elements
        int sz; // the number of elements
};

Then we wrote a read_and_sum function:

Vector v(6); // a Vector with six elements

double read_and_sum(int s)
{
    Vector v(s); // make a vector of s elements
    for (int i=0; i<v.size(); ++i) std::cin>>v[i]; // read into elements
    double sum = 0;
    for (int i=0; i<v.size(); ++i) sum+=v[i]; // take the sum of the elements
    return sum;
}

I wrote the main() to print out the sum and the elements in my vector:

int main(){
    std::cout << read_and_sum(6); \\print the sum
    for (int i=0; i<v.size(); ++i) std::cout<< v.operator[](i) << "\n"; \\print each value in vector

After I run the program, I input six numbers first and I saw the correct sum. But I got 6 crazy numbers like 646.82957e-318 when I tried to print the number I just entered. What did I do wrong?

1 Answers1

2

v and v are two separate vectors. Now you might be thinking "huh? Didn't you just say the same thing twice?" but that's exactly what you're doing in the code!

Vector v(6); // a Vector with six elements

Defines a v in the global scope. This is what you later reference in main() when you try to print your vector.

double read_and_sum(int s)
{
    Vector v(s); // make a vector of s elements

Defines a v in the read_and_sum() function scope. This is what you populate from std::cin.

scohe001
  • 15,110
  • 2
  • 31
  • 51
  • Thanks a lot! But how should I reference the v later if I Defines the v in the function scope? – David Nie Dec 01 '20 at 21:27
  • @YBCO_David if you define `v` in the function scope, it'll be destroyed when the function ends (though any dynamically allocated memory won't. So right now you'll have memory leaks!). You could return a copy of `v` (in which case you'll need to define and implement a copy constructor) or just do all your work in the function. – scohe001 Dec 01 '20 at 21:29
  • Thanks! I have to say that c++ is a lot different than python. – David Nie Dec 01 '20 at 21:32
  • Ha. That's for sure. A lot less is magically done for you in C++. If you do define a copy constructor, I'd advise looking into [the Rule of Three](https://stackoverflow.com/q/4172722/2602718) (which would also help prevent the leaks you already have in your program) @YBCO – scohe001 Dec 01 '20 at 21:33