The expression must have class type is an error that is thrown when the dot(.) operator is used to access an object’s properties, is used on pointers to objects.
Dot(‘.’) Operator is basically used for accessing the fields and methods of an object, but when a dot operator is used on the pointer to object in that condition, the error “Expression must have class” type is shown.
When the Dot(‘.’) operator is used on a pointer of class types object in that condition Dot(‘.’) Operator tries to find fields and methods of pointer type but in reality, they do not exist and because of that, we get this error.
Below is the code below to illustrate the above error:
C++
#include <iostream>
using namespace std;
class GeeksforGeeks {
public :
void showMyName()
{
cout << "Welcome to GeeksforGeeks!" ;
}
};
int main()
{
GeeksforGeeks* p = new GeeksforGeeks();
p.showMyName();
return 0;
}
|
Output:
How to resolve this error? To solve the above error, the idea is to initialize the class without using the new operator i.e., instead of initializing the object as “className *obj = new className()”, initialize it as “className obj” to access the member function of the class using dot(‘.’) operator. Below is the program to illustrate the same:
C++
#include <iostream>
using namespace std;
class GeeksforGeeks {
public :
void showMyName()
{
cout << "Welcome to GeeksforGeeks!" ;
}
};
int main()
{
GeeksforGeeks p;
p.showMyName();
return 0;
}
|
Output:
Welcome to GeeksforGeeks!
Time Complexity: O(1)
Auxiliary Space: O(1)
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
20 Jun, 2022
Like Article
Save Article