-1

If I have a class similar to this:

namespace Matrix {
  class Matrix; 
  class Vector {
   public:
    //i want to create a vector the same size as contents with the same values
    Vector(const std::vector<ValueType>& contents);
   private:
   std::vector<ValueType> contents;
}

When contents is passed in through the constructor, is it automatically copied to the vector called contents I defined within the class? Or is there something I have to do in the constructor definition to achieve that?

somelube
  • 29
  • 1

1 Answers1

0

No, you do not get automatic copying just by virtue of your constructor having an argument. You could write:

Vector(const std::vector<ValueType>& contents_) : contents{contents_} { };

which would do the copying. However, this whole approach is not a good idea, for two reasons:

  1. If you pass an rvalue to the constructor (e.g. a temporary vector you obtained from some function), a const & would make an extra copy.
  2. Why only be willing to initialize your data from an std::vector? You should be willing to accept at least a std::span, or perhaps template over a container or a pair of iterators.
  3. Actually, I would consider templating your entire inner vector class on the underlying container.
einpoklum
  • 118,144
  • 57
  • 340
  • 684
  • Its an assignment where I'm meant to define a bunch of already declared constructors and operators to create a matrix and vector class. I dont think I can change the constructor declaration – somelube May 27 '19 at 22:52