0

It seems that BoVector rhs1 and BoVector rhs2 can assign all elements by a = square(bv); successfully. But it might not be a case in a common assignment of one array to another, say

int b[2]{ 1,2,3 };
int c[2]{ 3,4,5 };
c = b; //it doesn't work 

c =b; will generate a compiler error. Why is that? since the code below, doesn't overwrite the operator= to be capable of array assignment.

P.S: Please DO NOT ask me what not to use or use in the comment section (this is like asking me delete the question and forget about it!). My question is why inside the class under the hood assigning arrays work but in a regular way it doesn't work!

template <typename T>
T square(T x)
{
    return x * x;
}
template<typename T>
class BoVector
{
private:
    T arr[1000];
    size_t size;
public:

    BoVector():
        size(0)
    {}
    void push(T x)
    {
        this->arr[this->size] = x;
        ++(this->size);

    }
    
    T get(int i) const
    {
        return arr[i];
    }
    size_t getSize() const { return this->size; };
    void print() const
    {
        for (size_t i=0;i<size;++i )
        {
            std::cout << this->arr[i] << '\n';
        }
    }
};
template<typename T>
BoVector<T> operator*(const BoVector<T>& rhs1, const BoVector<T>& rhs2 )
{
    BoVector<T> result;
    for (size_t i = 0; i < rhs1.getSize(); ++i)
    {
        
        result.push(rhs1.get(i) * rhs2.get(i));
        
    }
    return result;
}
int main()
{

    BoVector<int> bv;
    bv.push(2);
    bv.push(10);
    bv.push(3);
    bv.push(20);
    
    BoVector<int> a;
    a = square(bv); //it works perfectly
    a.print();

    int b[2]{ 1,2,3 };
    int c[2]{ 3,4,5 };
    c = b; //it doesn't work 

    
}
Sami
  • 513
  • 4
  • 11
  • The things you are comparing aren't doing the same thing. – sweenish Jan 05 '23 at 19:02
  • Arrays are the product of the time in which they were created and due to the memory and processing power limitations of the 1970s, you can consider arrays to be ing stupid today. There is a lot you just can't do with them. Use `std::array` or `std::vector` instead. – user4581301 Jan 05 '23 at 19:03
  • 1
    The default assignment operator for a structure is smart enough to copy its contents, including an array. The array just isn't so lucky. Why? Literally because the language standard document says so. – user4581301 Jan 05 '23 at 19:05
  • Why has this not been changed as computers got better endowed? Because that would break all of the old programs expecting a particular set of behaviours AND because we have stuff like `std::array` and `std::vector` to the more complicated jobs. – user4581301 Jan 05 '23 at 19:10

0 Answers0