How to resolve the "expression must have class type" error in C++

The “expression must have class type” is an error that is thrown when the . operator, which is typically used to access an object’s fields and methods, is used on pointers to objects.

When used on a pointer to an object, the . operator will try to find the pointer’s fields or methods, but it won’t, because they do not exist. These fields or methods are part of an object, rather than a part of the pointer to an object.

svg viewer

Wrong code

The code below tries to apply the . operator on a pointer to an object, rather than on an object itself. The code throws an "expression must have class type"​ error.

#include <iostream>
using namespace std;
class Myclass
{
public:
void myfunc() {
cout<<"Hello World"<<endl;
}
};
int main()
{
// A pointer to our class is created.
Myclass *a = new Myclass();
// myfunc is part of the class object, rather than
// part of the pointer to that class' object.
a.myfunc();
}

Correct code

The code below correctly applies the . operator on an object to access the object’s member functions. Since a is now a class object, the code does not throw any error.

#include <iostream>
using namespace std;
class Myclass
{
public:
void myfunc() {
cout<<"Hello World"<<endl;
}
};
int main()
{
// A class object of Myclass is created.
Myclass a ;
// The . operator is used to access the class' methods.
a.myfunc();
}

Copyright ©2024 Educative, Inc. All rights reserved