Solution:
The “expression should have class type” is an error that is thrown at the time the . operator, which is generally applied to access an object’s fields and methods, is used on pointers to objects.
At the time applied on a pointer to an object, the . operator will attempt to trace the pointer’s fields or systems, however it won’t, since they do not subsist. These fields or methods are part of an object, more than a part of the pointer to an object.
Wrong code
The code below attempts to imbed the . operator on a pointer to an object, more than on an object itself. The code throws an "expression should have class type" error.
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();
}#include <iostream>
Correct code
The code below accurately embeds the . operator on an object to access the object’s member functions. Because a is now a class object, the code does not throw any error.
#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();
}