I am trying to use the increment operator in a derived class. But I am not able to achieve this.
#include<iostream>
using namespace std;
class Base {
private:
int a;
public:
int x, y, z;
int Converter(int data) {
cout << "Printing z: " << z << endl;
return data * x + y;
}
Base& operator=(int rhs) {
a = Converter(rhs);
return *this;
}
Base(int a, int x, int y, int z) : a(a), x(x), y(y), z(z) {}
explicit Base(int a_) : a(a_) {}
Base operator+(const Base& obj){
Base x(*this);
return Base(x.a + obj.a);
}
Base& operator++() { return *this = *this + Base(Converter(1)); }
};
class Derived : Base {
public:
Derived() : Base(0, 1, 2, 3) {} // Come constants for x, y, z
explicit Derived(int data) : Base(data, 1, 2, 3){}
using Base::operator=;
using Base::operator++;
};
int main(){
Derived x(10);
++x;
x = 1;
}
I am thinking the problem is with the highlighted line that was commented above. When I tried to print the values x, y, z in the operator++() function it is showing 0 eventhough I have initialized them as 1, 2, 3 in the Derived class definition.
I tried to call the other constructor as below but still no use.
Base& operator++() { return *this = *this + Base(Converter(1), this->x, this->y, this->z) }
The output produced is:
Printing z: 3
Printing z: 0
If I invert the order in main() like below, the output is different.
x = 1;
++x;
Output:
Printing z: 3
Printing z: 3
Can someone point me in the right direction?
Thanks.