Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialization of a pointer

Tags:

c++

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 ?)

like image 211
Rajeshwar Avatar asked Mar 15 '13 22:03

Rajeshwar


People also ask

What is the initialization of pointer?

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 .

How pointers are declared and initialized in C?

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.


2 Answers

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.

like image 130
Andy Prowl Avatar answered Oct 16 '22 16:10

Andy Prowl


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.

like image 28
Mankarse Avatar answered Oct 16 '22 17:10

Mankarse