0

I want to add value using operator overloading or any other method. If I have class abc that class have 2 integer array I want to add value like this( abc object; object= object+4;)if I do this then 4 will be insert in array.

class abc{
 int array1[10];
 int array2[10];
 public:
 abc(int a[],int b[])
 {
     array1=a;
     array2=b;
  }
  };
  int main()
  {  
     int ar1[]={1,2,3};
     int ar2[]={4,5,6};
     abc object(ar1,ar2);
     object =object+4;
    }

I want if I write (object=object+4;)then this line will insert 4 in array1 at index 3, is it possible?

Scheff's Cat
  • 19,528
  • 6
  • 28
  • 56
john
  • 79
  • 7
  • 1
    I'm sure someone will answer fully, but if you were to replace your arrays with `std::vector`, the issues will fall away. – Bathsheba Jan 15 '21 at 09:06
  • 1
    Yes, it is possible.Start with [What are the basic rules and idioms for operator overloading?](https://stackoverflow.com/questions/4421706/what-are-the-basic-rules-and-idioms-for-operator-overloading?) – molbdnilo Jan 15 '21 at 09:08
  • It's hard to understand what you mean. Does the code you show compile? Use `std::array` or `std::vector` at least as the class members. The constructor need to know the size of C-style arrays if you insist on using them. I guess you should start from overloading `operator+=`, but for this you need to read a book, manual, etc. – zkoza Jan 15 '21 at 18:01

1 Answers1

1

You might do:

class abc
{
    std::vector<int> array1;
    std::vector<int> array1;
public:
    abc(std::vector<int> a, std::vector<int> b) :
        array1(std::move(a)), array2(std::move(b))
    {}

    abc& operator += (int n) { array1.push_back(n); array2.push_back(n); return *this;} 
};

int main()
{  
    abc object({1, 2, 3}, {4, 5, 6});
    object += 4;
}
Jarod42
  • 203,559
  • 14
  • 181
  • 302
  • 2
    Indeed - look how much simpler it is with `std::vector`. Upvote coming. Note the new fashion in passing parameters by value, then using `std::move`. – Bathsheba Jan 15 '21 at 09:39
  • without vector is it possible ? – john Jan 15 '21 at 12:23
  • Without vectors, you have to keep track of size (that you already don't in you invalidate constructor). – Jarod42 Jan 15 '21 at 15:50