2

Possible Duplicate:
what is the difference between (.) dot operator and (->) arrow in c++

I'm trying to learn c++, but what I don't understand is the different between "->" and "." when calling a method.

For example, I have seen something like class->method(), and class.method().

Thanks.

2
  • And what is the type of class in either case? Commented Aug 11, 2010 at 22:09
  • Time to get a good book and find out. Commented Aug 11, 2010 at 22:45

6 Answers 6

4

In a normal case, a->b is equivalent to (*a).b. If a is a pointer, -> dereferences it before accessing the element.

Sign up to request clarification or add additional context in comments.

Comments

1

The -> operator calls a method on the object pointed to by a pointer.

The . operator calls a method on an object itself.

If a is a pointer, a->b() is equivalent to (*a).b().

Comments

1

You use -> when the thing on the left is a pointer to an object. You use '.' when the thing on the left is the object itself.

Comments

0

When your calling a method through a pointer, you use ->; otherwise, use ..

Example:

MyClass* obj = new MyClass(); obj->myMethod(); MyClass obj2; obj2.myMethod(); 

Comments

0

It is maybe a bit irritating at first but C/C++ differenciates calling a method through the use of a pointer (use of ->) or through the use of a variable/reference (use of .). So the type of variable you use decides whether you call with the one or with the other option.

Note that in many other programming languages (Java, C#, ...) this is not the case.

Comments

0

You will never see class.method() or class->method() in C++. What you will see is object.method(), obj_ptr->method() or class::method(). When you make an object of a class, you use the . operator, when refering to a pointer to an object, you use -> and when calling a static method directly without making an object, you use ::. If you have a class a_class like below, then:

class a_class { public: void a_method() { std::cout<<"Hello world"<<std::endl; } static void a_static_method() { std::cout<<"Goodbye world"<<endl; } } int main() { a_class a_object = a_class(); a_class* a_pointer = new a_class(); a_object.a_method(); //prints "Hello world" a_object->a_method(); //error a_object::a_method(); //error a_pointer.a_method(); //error a_pointer->a_method(); //prints "Hello world" a_pointer::a_method(); //error *a_pointer.a_method(); //prints "Hello world" *a_pointer->a_method(); //error *a_pointer::a_method(); //error a_class.a_method(); //error a_class->a_method(); //error a_class::a_method(); //error because a_method is not static a_class.a_static_method(); //error a_class->a_static_method(); //error a_class::a_static_method(); //prints "Goodbye world" } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.