Trusted answers to developer questions

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

Get Started With Machine Learning

Learn the fundamentals of Machine Learning with this free course. Future-proof your career by adding ML skills to your toolkit — or prepare to land a job in AI or Data Science.

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.

Press + to interact
#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.

Press + to interact
#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();
}

RELATED TAGS

c++
class
type
pointer
Copyright ©2024 Educative, Inc. All rights reserved
Did you find this helpful?