Can you tell me the difference between a . and -> call to a method in C++.
This code works fine, using both calling methods.
#include <iostream>
using namespace std;
class myclass
{
public:
string doSomething();
};
string myclass::doSomething()
{
return "done something\n";
}
int main (int argc, const char * argv[])
{
myclass c;
std::cout << c.doSomething();
myclass *c2;
std::cout << c2->doSomething();
return 0;
}
I don’t understand the different between the 2 calls? they both work?
The arrow operator is meant for calling a method from a pointer to an instance of an object.
The dot operator is meant for calling a method from a reference to an instance of an object, or on a locally defined object.
Your code would not compile if you reversed the operators on the two examples.