I am currently confused with the following statement - I though this statement would yield an error during compile time however it doesn't.
// statement 1:
someclass* q(someclass());
I understand if the statement was like this
// statement 2:
someclass* q(&someclass());
I would like to know why statment 1 doesnt generate an error or even if that is valid (is there anything I am missing behind the scenes ?)
The initializer is an = (equal sign) followed by the expression that represents the address that the pointer is to contain. The following example defines the variables time and speed as having type double and amount as having type pointer to a double .
While declaring/initializing the pointer variable, * indicates that the variable is a pointer. The address of any variable is given by preceding the variable name with Ampersand & . The pointer variable stores the address of a variable. The declaration int *a doesn't mean that a is going to contain an integer value.
I would like to know why statment 1 doesnt generate an error or even if that is valid
The first statement is valid, although it is probably not doing what you expect: this statement is declaring a function named q
which returns a pointer to an object of type someclass
and takes in input a function which in turn accepts no arguments and returns an object of type someclass
. This is called the Most Vexing Parse.
The second statement is not valid: it is trying to declare a pointer named q
to an object of type someclass
, and initialize this pointer to the address of the object constructed by the someclass()
expression. Notice, however, that someclass()
is a temporary, and taking the address of a temporary is illegal.
Statement 1 is actually a declaration for a function. This function is called q
, and takes a pointer to a function taking no arguments and returning a someclass
, and returns a pointer to someclass
.
See Most Vexing Parse.
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