Skip to content
Related Articles

Related Articles

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



filter_none

edit
close

play_arrow

link
brightness_4
code

// 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;
}

chevron_right


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

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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;
}

chevron_right


Output:

Welcome to GeeksforGeeks!

Attention reader! Don’t stop learning now. Get hold of all the important C++ Foundation and STL concepts with the C++ Foundation and STL courses at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up
Recommended Articles
Page :