Riko Riko - 1 year ago 70
C++ Question

C++ What is the difference between definition and instantiation?

What is the difference between definition and instantiation?

Sub-question: Are "variable definition" and "variable instantiation" the same?

int x;

The above code can be reffered to as both a variable definition as well as a variable instantiation, right? If so, my question is if these two terms are synonyms? (or is there a different relation between them?)

Answer Source

There are:

1) variable definitions,

2) variable/object instantiations, and

3) template instantiations.

1 & 3 are specific C++ terminology. 2 is more general terminology that might be used with C++. It is not an "officially" defined term for C++.

I understand that your question is about 1 and 2, but not 3. 3 is different than 2, though related in meaning. I won't address 3 further as I don't believe it is part of your question.

Instantiation is the creation of an object instance. It is more usual to use the term in reference to a class object than something like an int or double.

A C++ variable definition does cause an object of the type being defined to be instantiated. It is, however, possible in C++ to instantiate an object other than via a variable definition.

Example 1:

std::string name;

The variable name, a std::string, is defined and (at run-time) instantiated.

Example 2:

std::string *namePointer;

The variable namePointer, a pointer, is defined and might be said (at run-time) to be instantiated (though not initialized). There is no std::string variable and no std::string is instantiated.

//simple example, not what one should usually write in real code
namePointer = new std::string("Some Text");

No additional variable is defined. A std::string object is instantiated (at run-time) and the separate and pre-existing namePointer variable also has its value set.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download