Class in constructor won't decrease

When you run the program it prints out the same number twice and it seems like the constructor number doesn't decrease which is 100. Just run it it prints out 98 twice. I have no idea why the 100 just don't decrease at all please tell me why thanks.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#include <iostream>
#include <vector>


class owner{

public:
    owner(int d) : money(d) {};
    owner();
int x;
int y;
     int buysomething(owner *m,int element);

private:
    int money;

};
int owner::buysomething(owner *m,int element){

if(m->money < element || m->money == element){

    std::cout << "You can't buy this" << std::endl;
    std::cout << m->money << std::endl;

} else if(m->money > element){

return m->money - element;
std::cout << m->money << std::endl;
}

}

int main()
{
    owner q(100);

    int o = 3;
   std::cout <<  q.buysomething(&q,o);
   std::cout << q.buysomething(&q,o);

}
I don't see at all why would money decrease.

Which statement should be decreasing the money?

Also, this example shows that you don't understand how to properly access class' data members.
Buysomething should be decreasing the money. and it does decrease it just doesn't stay decreased. It kinda resets in main.
Which statement in Buysomething? Quote the exact statement, not the entire function.
 
return m->money - element;
That statement doesn't change money because changing the money requires the assignment operator.

like:

money = money - element;

From what you have been posting, I think that it is likely that you have jumped into classes too soon without even understanding functions. I would suggest that you practice essentials more and get a better understaning before trying to learn classes. Especially, learn more about functions and do some practice.
Last edited on
Nah, I just didn't know what to do thanks though.
> q.buysomething(&q,o);
a member function of a class receives as a hidden parameter the memory address of the object that effectuates the call (the this pointer)

So passing yourself that memory address is error prone and unnecessary


1
2
3
4
5
6
7
int owner::buysomething(int cost){
//...
   this->money -= cost;
//...
}

q.buysomething(o); //chose better names 
Topic archived. No new replies allowed.