Home > Software design >  C Inheritance and passing vector references
C Inheritance and passing vector references

Time:01-01

Given the following code compiles and runs with no error

class A {
public:
  std::vector<int> i;
  void add(std::vector<int> &v) { i = v; }
};

class B {
public:
  B(A &a, std::vector<int> &v) { a.add(v); }
};
int main() {
  A a;
  std::vector<int> v{1, 2, 3, 4};
  B b(a, v);
  return 0;
}

If I add a class C

class C : B {
public:
  std::vector<int> v{1, 2, 3, 4};
  C(A &a) : B(a, v) {}
};

and change main

int main() {
  A a;
  C c(a);
  return 0;
}

I get

terminate called after throwing an instance of 'std::bad_array_new_length'
  what():  std::bad_array_new_length
zsh: IOT instruction (core dumped)

I don't even know how to title this because I don't understand why this would possibly fail

I was expecting the second version of main to do the same as the first version of main but it gives a strange error that makes no sense to me

CodePudding user response:

One possible solution:

class C : B {
public:
  std::vector<int> v;
  C(A &a) : C(a, {1, 2, 3, 4}) {}
private:
  C(A& a, const std::vector<int>& vv)
    : B(a, vv), v(vv) {}
};

This attempts to preserve the semantics of the original code to the extent possible (even while they don't necessarily make sense to me).

  • Related