I am reading a book and it says that there is no difference between initialization and assignment for the built-in type in C
or C++
, but the type like string
in C++
, there are difference. Why? Why there is no difference for the built-in types in C
?
What is the difference between initialization and assignment? Initialization gives a variable an initial value at the point when it is created. Assignment gives a variable a value at some point after the variable is created.
Initialization is the process of assigning a value to the Variable. Every programming language has its own method of initializing the variable. If the value is not assigned to the Variable, then the process is only called a Declaration.
In addition, when variables are initialized upon declaration, more efficient code is obtained than if values are assigned when the variable is used. A variable must always be initialized before use. Normally, the compiler gives a warning if a variable is undefined. It is then sufficient to take care of such cases.
Initialization: Assigning a value to a variable is called initialization. For example, cost = 100. It sets the initial value of the variable cost to 100. Instantiation: Creating an object by using the new keyword is called instantiation.
Because the standard types like int
don't have constructors. These
int x = 123;
int y;
y = 123;
are the same (at the beginning, y
will have some random/garbage value).
While creating an object will call its constructor. So, for example:
std::string s = "123";
std::string y;
y = "123";
s
will be created and initialized immediately, while y
will be created, its values will be initialized (based on std::string
's constructor) and later, they will be changed during the operator=
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With