Thisaru Guruge Thisaru Guruge - 16 days ago 8
C++ Question

variable has initializer but incomplete type C++

I am new to C++. I have this code to create a struct, to show the usage of

keyword in C++.

#include <iostream>

using namespace std;

int main()
mutable double radius;
double PI = 3.142;

double getArea()
return (PI * radius * radius);
} circle;

const struct circle c1 = {2.0};
circle.radius = 7;

cout << "Area is " << circle.getArea() << endl;

return 0;

But I get the following error message when compiling:

error: variable const main()::circle c1 has initializer but incomplete type

Error is at
in the line
const struct circle c1 = {2.0};
. Can anyone point me out the error here.


When you put the name circle after the right brace at the end of the struct definition, you're declaring a variable.

Put it at the start, after the word struct, to declare a type.


struct circle
    // ...

In other news:

  • You'll need to declare getArea() as const to be able to call it on a const instance, i.e. double getArea() const.

  • You don't need the return 0; at the end, because that's the default for main. There is no such default for other functions. main is special.

  • In order to use cout unqualified (as it seems you want to) you can add using namespace std; at the start of the code; it's usually placed after the includes.

mutable is usually not used to allow outside code to treat part of an object as always non-const.

Instead it's used as a device to more easily let a class implementation have some non-const state also when the object appears to be const to outside code. That's called logical constness. For example, the object might cache the result of an expensive computation, even when it's const.

In C++17 and later mutable can also be applied to lambda expressions, where it yields a lambda that can change its state (captured values).