I searched for my problem for more than 3 hours but couldn't find any good articles about so decided to post a question here to ask for your advice. My problem is I don't understand how class works. It is just a simple class but in one case it doesn't work. First, below is the code that works
class R{
int x, y;
public:
R();
R(int a, int b) : x(a), y(b) {};
void setX(int a){ x = a; }
void setY(int b){ y = b; }
int getX(){ return x; }
int getY(){ return y; }
void display();
};
void R::display(){
// displaying x and y I removed the function because it somehow remove the rest of the code after arrow operator
}
int main(){
R r(2,3);
r.setX(1);
r.setY(2);
r.display();
}
but when I change the main like this it doesn't work
int main(){
R r;
r.setX(1);
r.setY(2);
r.display();
}
I first thought the reason might be that I didn't actually created an instance but found a code that works fine from a website. The code was like this:
// overloading operators example
#include
using namespace std;
class CVector {
public:
int x,y;
CVector () {};
CVector (int a,int b) : x(a), y(b) {}
CVector operator + (const CVector&);
};
CVector CVector::operator+ (const CVector& param) {
CVector temp;
temp.x = x + param.x;
temp.y = y + param.y;
return temp;
}
int main () {
CVector foo (3,1);
CVector bar (1,2);
CVector result;
result = foo + bar;
// displaying x and y I removed the function because it somehow remove the rest of the code after arrow operator
return 0;
}
It also just made an instance "CVector temp" not "CVector temp(2,3)" but it works fine while mine is not working.
If anyone knows what I am missing and the problem of my code, could you please give me your advice?
Thanks for reading and your time