-2

I have my own Class Vector and I'd like to create an operator-- to delete last element in array. But in my implementation i got an error:

binary "--": Vector does not define this operator or a conversion to a type acceptable to the predefined operator.

How do i declare it correctly?

class Vector {
private:
    int *vect;
    int size;
public:
    void operator--();
}
void Vector::operator--() {
    int *tmp = vect;
    size--;
    vect = new int(size);
    for (int i = 0; i < size; i++) vect[i] = tmp[i];
    delete[] tmp;
}
pookeeshtron
  • 135
  • 1
  • 1
  • 8
  • 1
    How did _you_ declare it? – tkausl Nov 25 '18 at 20:36
  • @tkausl void operator--(); – pookeeshtron Nov 25 '18 at 20:37
  • 1
    Post your code in the question. – Filip Vondrášek Nov 25 '18 at 20:40
  • As to your implementation, all you need to do is simply subtract 1 from the `size` variable. You don't need to reallocate and recopy anything. Isn't it `size` that determines the number of elements? And I agree with the previous comment -- this should be a `pop_back()` function, not an overloaded `--`. – PaulMcKenzie Nov 25 '18 at 20:55
  • @FilipVondrášek done – pookeeshtron Nov 25 '18 at 20:58
  • @PaulMcKenzie I thought of it, just can't check because of compilation error. – pookeeshtron Nov 25 '18 at 20:59
  • 2
    @pookeeshtron [Please read the following](https://stackoverflow.com/questions/4421706/what-are-the-basic-rules-and-idioms-for-operator-overloading). – PaulMcKenzie Nov 25 '18 at 21:02
  • @PaulMcKenzie I just got a task to impliment it as --. Anyway thanks, I alreayd found the solution. – pookeeshtron Nov 25 '18 at 21:03
  • 1
    Even if you fix the declaration, the implemention is still wrong. `new int(size)` needs to be `new int[size]` instead. And the code doesn't account for the possibility of `size` being 0, or the possibility of `new` throwing an exception. And really, there is no need to reallocate `vect` at all, decrementing `size` is sufficient by itself, if you simply add a `capacity` member to the class so the allocated size can be different than the populated size. – Remy Lebeau Nov 25 '18 at 21:46

1 Answers1

-2

I should have declared it like this:

void operator--(int);

And implemented like this:

void Vector::operator--(int) {
    if (size>1) size--;
    else std::cout << "Only one element in vector.\n";
}

this (int) helps the compiler to differ prefix and postfix increments or decrements.

An example:

struct A {
    void operator --(int) { std::cout << "Postfix\n"; }
    void operator --() { std::cout << "Prefix\n"; }
};

int main()
{
    A a;
    a--;
    --a;
}

Thanks to @PaulMcKenzie for the link.

pookeeshtron
  • 135
  • 1
  • 1
  • 8