Cynizm
Cynizm

Reputation: 99

calling class function inside other class function c++

My program is working fine and does what its supposed to do but the notation used doesn't seems right to me. I have a class with some variables and two functions:

foo.h

class foo{
private:
    int a;
public:
    void seta1(int value);
    void seta2(int value);
};

foo.cpp

void foo::seta2(int value)
{
     a = value;
}

void foo::seta1(int value)
{
    seta2(value);
}

then when i print variable a it has the value its supposed to have, but wouldn't this notation be more correct?

void foo::seta2(int value)
{
     this.a = value;
}

Upvotes: 1

Views: 1330

Answers (2)

J-Mik
J-Mik

Reputation: 896

actually it should be this->a, since this is a pointer. however you don't need to usually write "this" since it's implied. both are correct.

This is only useful if a member variables is over-ridden by a local variable.

For example:

void foo::seta2(int a)
{
     this->a = a;
}

Upvotes: 2

Peter
Peter

Reputation: 36597

No. this is a pointer, not a reference.

this->a = value would be correct.

The this-> is implied in this case (a a non-static member being accessed in a non-static member function). There are some circumstances where the this-> is required, but this is not one of them.

Upvotes: 4

Related Questions