2

I have a class A whose constructor takes as one of its arguments as an std::valarray[^1], however I have found that its values change to large random numbers once the constructor has finished.

As an aside, there could be an issue with my getters and setters, which I just started using in the cotext of C++ with the help of this SO question and 18.3.5 Accessor Functions from Stroustrup's The C++ Programming Language.

Stroustrup's format of constexpr double real() const { return re; } is what my example ended up using, however without constexpr since my class didn't like it (I'm trying to understand why but still haven't got it yet).

A comment on the accepted answer of my question by user deidei says that std::valarray is "dynamic", which I guess here means that you can resize it. That might bring issues when it comes to memory, and I think that my values might have been overwritten somehow due to this fact.

#include <iostream>
#include <valarray>
#include <vector>

class A
{
public:
  A(std::valarray<int> b, std::vector<int> c)
  {
      std::cout<< b[0]  << std::endl;
  };

  std::valarray<int> get_b() const {return b;};
  std::vector<int> get_c() const {return c;};

private:
  std::valarray<int> b;
  std::vector<int> c;
};

int main()
{
  std::valarray<int> b = {1, 3};
  std::vector<int> c = {4, 2, 8, 17};

  A a(b,c);
  std::cout<< a.get_b()[0] << std::endl; // returns a random large number such as 26618992

  return 0;
}

What issue might be causing this problem?

[^1]: (inspired by the answer to my previous question, for those of you playing along at home)

Prunus Persica
  • 1,173
  • 9
  • 27

1 Answers1

2

My understanding was that since the constructor takes b and c as arguments then they will be assigned to member variables of the same name

This is incorrect. You can initialize member variable via member initializer list, via default initialization or by assigning values directly in the body of constructor. For example:

A(std::valarray<int> b, std::vector<int> c)
  : b(b), c(c)
{...

or

private:
  std::valarray<int> b = {1, 3};
  std::vector<int> c = {4, 2, 8, 17};

or

A(std::valarray<int> b, std::vector<int> c)
{
    this->b = b;
    this->c = c;
    ...

You have done none of the above, so your valaray of int's is size of 0. When you return its copy and trying to access non-existing element

// returns a random large number such as 26618992

you get some garbage value from the memory.

Killzone Kid
  • 6,171
  • 3
  • 17
  • 37