glucomine
glucomine

Reputation: 35

c++ initializing struct with struct pointer

While I was reading C++Primer, I came across this code

struct destination;
struct connection;
connection connect(destination*);

What does connection connect(destination*); line do? and how come it compiles fine even though it's passing the struct name? Aren't you supposed to initialize the struct to variable then pass that like so?

struct destination;
struct connection;
destination dest;
connection connect(dest);

Upvotes: 2

Views: 115

Answers (1)

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385395

What does connection connect(destination*); line do?

It declares a function called connect, that takes a destination* and returns connection.

In this declaration, a name is not provided for the parameter (which, though not particularly helpful to the reader, is valid). Presumably, that'll be provided when the function is defined, like so:

connection connect(destination* ptr)
{
   connection conn;
   // do something with conn and ptr
   return conn;
};

The rest of the book's code snippet (the part that you did not quote) shows a call to the function connect, from within another function called f.

Function declarations were covered six chapters prior.

how come it compiles fine even though it's passing the struct name?

Because that's what you're supposed to do in a function declaration.

Aren't you supposed to initialize the struct to variable then pass that like so?

No.

Upvotes: 6

Related Questions