0

Inside setMyInt function I have used two statements to set myInt variable. Though both of them gives me the same result. Is there any conceptual difference in working of them?

#include <iostream>
using namespace std;
class Bar{
    int myInt;

public:
    const int getMyInt() const {
        return myInt;
    }

    void setMyInt(int myInt) { 

        Bar::myInt = myInt;
       this->myInt=myInt;
    }
};

int main(){
    Bar obj;
    obj.setMyInt(5);
    cout<<obj.getMyInt();
    return 0;
}
Drew Dormann
  • 59,987
  • 13
  • 123
  • 180
  • related: https://stackoverflow.com/questions/4984600/when-do-i-use-a-dot-arrow-or-double-colon-to-refer-to-members-of-a-class-in-c – NathanOliver Feb 16 '18 at 19:35
  • The result is the same, but they mean different things `this` is a pointer to your object. While :: is for scoping and here it says that you want to use the `myint` variable that is a member of your class and not the argument. – Hans Lehnert Feb 16 '18 at 19:36
  • 2
    You need an example that has inheritance to observe a difference. – François Andrieux Feb 16 '18 at 19:36

2 Answers2

2

You can't really compare them, and they are not interchangeable, but because in C++ you can leave certain things out in certain cases, here it looks like they are.

In fact, both lines are short for:

this->Bar::myInt = myInt;

This means, set the value of the object Bar::myInt (the member called myInt in the scope of the class Bar), which is encapsulated by the object pointed to by this, to the value of the (other) variable myInt.

You can leave out Bar:: because this is a Bar* so that's implicit; you can leave out this-> because you're in a member function so that's implicit too.

More generally, -> performs a pointer dereference and object access, whereas :: is the "scope resolution operator" which fully qualifies a name.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
-1

“->” is used as a pointer “.” Is used for object members variables/ methods “::” Is used for static variables/ methods or for objects from another scope.

dbeach22
  • 19
  • 1