Search code examples
c++classnew-operator

Expression must have class type


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
  }
}

Solution

  • It's a pointer, so instead try:

    a->f();
    

    Basically the operator . (used to access an object's fields and methods) is used on objects and references, so:

    A a;
    a.f();
    A& ref = a;
    ref.f();
    

    If you have a pointer type, you have to dereference it first to obtain a reference:

    A* ptr = new A();
    (*ptr).f();
    ptr->f();
    

    The a->b notation 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 the -> operator to refer to the pointed object:

    auto ptr = make_unique<A>();
    ptr->f();