Skip to content
Related Articles

Related Articles

Improve Article

Expression must have class type error in C++

  • Last Updated : 14 Jan, 2021

The expression must have class type is an error that is thrown when the dot(.) operator is used to access an object’s prpperties, 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 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!
Want to learn from the best curated videos and practice problems, check out the C++ Foundation Course for Basic to Advanced C++ and C++ STL Course for foundation plus STL.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.



My Personal Notes arrow_drop_up
Recommended Articles
Page :