Pat Sch Pat Sch - 17 days ago 10
C++ Question

(C++) Incrementing via Pointer, or: Why is this not working? Pointer->int = Pointer->int+1;

I am learning some C++ but obviously my brain is still in Java-Mode.

I try to increment an integer variable which is a class variable of another class, to which I have got a pointer as member variable in my active class.

So the basic structure:

class A{
public:
int i=0;
}

class B{
public:
A* a;
void incrementA();
}

void incrementA(){
a->i=a->i+1;
}


For some reason it still returns 0, while:

a->i=1;


returns 1.

Is there some kind of mechanism that prevents me from accessing variables via pointers?

Answer
void incrementA(){
a->i=a->i+1;
}

this function doesnt belong to class B

you are just defining a standalone function, thats now how you define a member function outside the class.

you should define it like this:

void B::incrementA()
{
  //body
}

while a->i=1; returns 1.

that is because you are assigning it to 1

the implementation of your incrementA is correct in both semantic and syntax.

`a->i+=1;` 

will also do.

To fix this:

the creator of thread said:

Hey everyone, sorry for bothering you, i finally found the problem: In the destructor of B i decrement a->i, and I didnt know that emplace_back() uses the destructor to remove the buffered object :(