2

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);
0

1 Answer 1

6

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.

Sign up to request clarification or add additional context in comments.

2 Comments

ok that makes sense. I was confused if it was making a connection struct called connect or it was a function returning a connection
@qwertyz: The only way to really tell is exactly how you (almost!) did: where the type destination* is, this can only be a declaration. It wouldn't be valid to call a function (or, to initialise an object) like that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.