[c++] C++ variable has initializer but incomplete type?

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.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.cpp:

#include <iostream>
#include <string>

class Cat;

using namespace std;

int main()
{
    Cat Joey("Joey");
    Joey.Meow();

    return 0;
}

Cat_main.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;
}

This question is related to c++ class compiler-construction

The answer is


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.h

2) move

#include <string>

class Cat
{
    public:
        Cat(std::string str);
    // Variables
        std::string name;
    // Functions
        void Meow();
};

to Cat_main.h. Note that inside the header I removed using namespace std; and qualified string with std::string.

3) include this file in both Cat_main.cpp and Cat.cpp:

#include "Cat_main.h"

It's not related to Ken's case directly, but such an error also can occur if you copied .h file and forgot to change #ifndef directive. In this case compiler will just skip definition of the class thinking that it's a duplication.


You cannot define a variable of an incomplete type. You need to bring the whole definition of Cat into scope before you can create the local variable in main. I recommend that you move the definition of the type Cat to a header and include it from the translation unit that has main.


Sometimes, the same error occurs when you forget to include the corresponding header.


I got a similar error and hit this page while searching the solution.

With Qt this error can happen if you forget to add the QT_WRAP_CPP( ... ) step in your build to run meta object compiler (moc). Including the Qt header is not sufficient.


Questions with c++ tag:

Method Call Chaining; returning a pointer vs a reference? How can I tell if an algorithm is efficient? Difference between opening a file in binary vs text How can compare-and-swap be used for a wait-free mutual exclusion for any shared data structure? Install Qt on Ubuntu #include errors detected in vscode Cannot open include file: 'stdio.h' - Visual Studio Community 2017 - C++ Error How to fix the error "Windows SDK version 8.1" was not found? Visual Studio 2017 errors on standard headers How do I check if a Key is pressed on C++ How to enable C++17 compiling in Visual Studio? Remove from the beginning of std::vector Why does C++ code for testing the Collatz conjecture run faster than hand-written assembly? What is (x & 1) and (x >>= 1)? What are the new features in C++17? Visual Studio Code includePath Compiling an application for use in highly radioactive environments "No rule to make target 'install'"... But Makefile exists How to build and use Google TensorFlow C++ api Error LNK2019 unresolved external symbol _main referenced in function "int __cdecl invoke_main(void)" (?invoke_main@@YAHXZ) Converting std::__cxx11::string to std::string lvalue required as left operand of assignment error when using C++ How to overcome "'aclocal-1.15' is missing on your system" warning? MSVCP140.dll missing How to get image width and height in OpenCV? CMake error at CMakeLists.txt:30 (project): No CMAKE_C_COMPILER could be found Reading json files in C++ What exactly is std::atomic? Compile c++14-code with g++ Visual Studio 2015 doesn't have cl.exe Visual Studio 2013 error MS8020 Build tools v140 cannot be found CMake does not find Visual C++ compiler Casting int to bool in C/C++ C++ How do I convert a std::chrono::time_point to long and back How can I get the size of an std::vector as an int? Significance of ios_base::sync_with_stdio(false); cin.tie(NULL); Fatal error: iostream: No such file or directory in compiling C program using GCC unresolved external symbol __imp__fprintf and __imp____iob_func, SDL2 How to end C++ code How to change text color and console color in code::blocks? Error: stray '\240' in program invalid use of non-static member function Convert float to string with precision & number of decimal digits specified? enum to string in modern C++11 / C++14 / C++17 and future C++20 Passing capturing lambda as function pointer How do I add a library path in cmake? error: expected primary-expression before ')' token (C) undefined reference to 'std::cout' java.lang.UnsatisfiedLinkError: dalvik.system.PathClassLoader fatal error: mpi.h: No such file or directory #include <mpi.h>

Questions with class tag:

String method cannot be found in a main class method Class constructor type in typescript? ReactJS - Call One Component Method From Another Component How do I declare a model class in my Angular 2 component using TypeScript? When to use Interface and Model in TypeScript / Angular Swift Error: Editor placeholder in source file Declaring static constants in ES6 classes? Creating a static class with no instances In R, dealing with Error: ggplot2 doesn't know how to deal with data of class numeric Static vs class functions/variables in Swift classes? Beginner Python: AttributeError: 'list' object has no attribute Call static methods from regular ES6 class methods How to implement private method in ES6 class with Traceur How do I correctly setup and teardown for my pytest class with tests? Calling one method from another within same class in Python What is the difference between static func and class func in Swift? Why Choose Struct Over Class? What's the difference between integer class and numeric class in R Getting error: ISO C++ forbids declaration of with no type undefined reference to 'vtable for class' constructor ES6 class variable alternatives Private properties in JavaScript ES6 classes c++ "Incomplete type not allowed" error accessing class reference information (Circular dependency with forward declaration) How to create multiple class objects with a loop in python? JavaScript: Create and destroy class instance through class method How to override the properties of a CSS class using another CSS class Best way to style a TextBox in CSS How would I access variables from one class to another? C++ [Error] no matching function for call to How do I get an object's unqualified (short) class name? Call a Class From another class Add and remove a class on click using jQuery? AttributeError: 'datetime' module has no attribute 'strptime' Select distinct using linq class method generates "TypeError: ... got multiple values for keyword argument ..." Abstract Class:-Real Time Example Why is enum class preferred over plain enum? Classes vs. Functions passing object by reference in C++ What does "Could not find or load main class" mean? jQuery select child element by class with unknown path add class with JavaScript How do I resolve ClassNotFoundException? Set Font Color, Font Face and Font Size in PHPExcel C# : Converting Base Class to Child Class Nested or Inner Class in PHP Arrays in type script Tkinter example code for multiple windows, why won't buttons load correctly? How to move div vertically down using CSS Creating a Zoom Effect on an image on hover using CSS?

Questions with compiler-construction tag:

fatal error C1010 - "stdafx.h" in Visual Studio how can this be corrected? Compilation error: stray ‘\302’ in program etc What is difference between sjlj vs dwarf vs seh? What is the difference between a token and a lexeme? How to compile makefile using MinGW? C++ variable has initializer but incomplete type? It is more efficient to use if-return-return or if-else-return? Could not load file or assembly ... The parameter is incorrect How do I compile the asm generated by GCC? Visual Studio: LINK : fatal error LNK1181: cannot open input file How does the compilation/linking process work? How to create a static library with g++? Compiler warning - suggest parentheses around assignment used as truth value How to install pywin32 module in windows 7 What's the difference between __PRETTY_FUNCTION__, __FUNCTION__, __func__? What is compiler, linker, loader? How to compile .c file with OpenSSL includes? Compiled vs. Interpreted Languages Clang vs GCC - which produces faster binaries? What is an application binary interface (ABI)? How can I set the PATH variable for javac so I can manually compile my .java works? Why GDB jumps unpredictably between lines and prints variables as "<value optimized out>"? Update GCC on OSX how does array[100] = {0} set the entire array to 0? Compiling with g++ using multiple cores C compiler for Windows? What does a just-in-time (JIT) compiler do? Where are static variables stored in C and C++?