简体   繁体   中英

Confusion about the difference between declarations and definitions in C++

I am confused. In part 3.8 of Bjarne Stroustrup's book 'Programming Principles and Practice Using C++' he talks about types of objects. I cite the following list:

  • A type defines a set of possible values and a set of operations (for an object).
  • An object is some memory that holds a value of a given type.
  • A value is a set of bits in memory interpreted according to a type.
  • A variable is a named object.
  • A declaration is a statement that gives a name to an object.
  • A definition is a declaration that sets aside memory for an object.

From his explanation of definition I understand that no memory is set aside for an object during declaration . However, the fact that Bjarne mentions that declaration involves the naming of an object, suggests that memory is actually set aside, as objects are explained as being

some memory that holds a value of a given type.

Can someone clarify this?

One of the complexities of C++ is that compilation is done in "translation units" (without seeing the whole program). Each translation units contains declarations of some parts defined in other translation units and definitions of some other parts. The declaration provides enough information to be able to generate code that uses the declared part once the address will be resolved by the linker.

Only one definition for an object or non-inline function is allowed in a program but there can be multiple declarations.

Things are indeed even more complex than this because of templates and some magic that C++ can do at link time (eg static variables in inline functions).

A declarations says "there is an object/function like this somewhere", a definition says "make an object/function like this".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM