Resolving the "cannot call member function without object" error

Share

The “cannot call member function without object” error is a common C++ error that occurs while working with classes and objects. The error is thrown when one tries to access the functions of a class without instantiating it.

svg viewer

Code

Consider the following C++ code snippets that depict the code with the error scenario and the correct code. The solution is to create an object of a class (instantiation) before using its methods.

#include <iostream>
using namespace std;
class Employee
{
public:
string name = "John";
int age = 25;
void printData()
{
cout << "Employee Name: " << name << endl;
cout << "Employee Age: " << age << endl;
}
};
int main()
{
Employee::printData();
return 0;
}
Copyright ©2024 Educative, Inc. All rights reserved