I have’t coded in c++ for some time and I got stuck when I tried to compile this simple snippet:
class A
{
public:
void f() {}
};
int main()
{
{
A a;
a.f(); // works fine
}
{
A *a = new A();
a.f(); // this doesn't
}
}
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
It’s a pointer, so instead try:
Basically the operator
.(used to access an object’s fields and methods) is used on objects and references, so:If you have a pointer type, you have to dereference it first to obtain a reference:
The
a->bnotation is usually just a shorthand for(*a).b.A note on smart pointers
The
operator->can be overloaded, which is notably used by smart pointers. When you’re using smart pointers, then you also use->to refer to the pointed object: