What it Means to Declare Something in C and C++
When you declare a variable, a function, or even a class all you are doing is saying: there is something with this name, and it has this type. The compiler can then handle most (but not all) uses of that name without needing the full definition of that name. Declaring a value--without defining it--allows you to write code that the compiler can understand without having to put all of the details. This is particularly useful if you are working with multiple source files, and you need to use a function in multiple files. You don't want to put the body of the function in multiple files, but you do need to provide a declaration for it.
So what does a declaration look like? For example, if you write:
int func();
This is a function declaration; it does not provide the body of the function, but it does tell the compiler that it can use this function and expect that it will be defined somewhere.
What it Means to Define Something in C and C++
Defining something means providing all of the necessary information to create that thing in its entirety. Defining a function means providing a function body; defining a class means giving all of the methods of the class and the fields. Once something is defined, that also counts as declaring it; so you can often both declare and define a function, class or variable at the same time. But you don't have to.
For example, having a declaration is often good enough for the compiler. You can write code like this:
int func();
int main()
{
int x = func();
}
int func()
{
return 2;
}
Since the compiler knows the return value of func, and the number of arguments it takes, it can compile the call to func even though it doesn't yet have the definition. In fact, the definition of the method func could go into another file!
You can also declare a class without defining it
class MyClass;
Code that needs to know the details of what is in MyClass can't work--you can't do this:
class MyClass;
MyClass an_object;
class MyClass
{
int _a_field;
};
Because the compiler needs to know the size of the variable an_object, and it can't do that from the declaration of MyClass; it needs the definition that shows up below.