Open In App

Expression must have class type error in C++

Last Updated : 20 Jun, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

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




// C++ program to illustrate the
// Expression must have class
// type error
#include <iostream>
using namespace std;
 
// Class
class GeeksforGeeks {
public:
    // Function to display message
    void showMyName()
    {
        cout << "Welcome to GeeksforGeeks!";
    }
};
 
// Driver Code
int main()
{
    // Object of the class
    GeeksforGeeks* p = new GeeksforGeeks();
 
    // Member function call
    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++




// C++ program to illustrate how to
// solve Expression must have class
// type error
#include <iostream>
using namespace std;
 
// Class
class GeeksforGeeks {
public:
    // Function to display message
    void showMyName()
    {
        cout << "Welcome to GeeksforGeeks!";
    }
};
 
// Driver Code
int main()
{
    // Object of the class
    GeeksforGeeks p;
 
    // Member function call
    p.showMyName();
 
    return 0;
}


Output:

Welcome to GeeksforGeeks!

Time Complexity: O(1)
Auxiliary Space: O(1)



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads