I am trying to compile 2 classes in C++ with the following command:
g++ Cat.cpp Cat_main.cpp -o Cat
But I receive the following error:
Cat_main.cpp:10:10: error: variable ‘Cat Joey’ has initializer but incomplete type
Could someone explain to me what this means? What my files basically do is create a class (Cat.cpp) and create an instance (Cat_main.cpp). Here is my source code:
Cat_main.cpp:
#include <iostream>
#include <string>
class Cat;
using namespace std;
int main()
{
Cat Joey("Joey");
Joey.Meow();
return 0;
}
Cat.cpp:
#include <iostream>
#include <string>
using namespace std;
class Cat
{
public:
Cat(string str);
// Variables
string name;
// Functions
void Meow();
};
Cat::Cat(string str)
{
this->name = str;
}
void Cat::Meow()
{
cout << "Meow!" << endl;
return;
}
You use a forward declaration when you need a complete type.
You must have a full definition of the class in order to use it.
The usual way to go about this is:
1) create a file
Cat_main.h2) move
to
Cat_main.h. Note that inside the header I removedusing namespace std;and qualified string withstd::string.3) include this file in both
Cat_main.cppandCat.cpp: