2

Im new in C++ and im trying to understand the logic behind using the keyword "using" in C++. This type of question might have been asked but i ran into problems trying to find useful information containing the word "using". What i want to do is to get a variable which is a pointer to a function, which returns a pointer to int and takes a pointer to int as parameter. What i tried to do:

definition of the function:

int* funct (int* p) {cout << "function called"; return p;}

Now here is what i would like to do if i was coding in C:

int* (*ptr)(int*) = &funct;

What i tried to do is :

using ptr = int* (*) (int*);

But when i try to use ptr like ptr = &func i get an error signalizing 'expected an identifier'. If you decide to help me please specify which * responds to which demand ("this * is here because you need pointer to a function" etc)

1
  • This is a bit opinion based, but I would recommend to avoid giving type aliases to pointers (including to functions) or references. That usually hurts the readability of the program. An exception is template argument dependent aliases such as those used in containers. Commented Nov 21, 2019 at 19:49

1 Answer 1

2

When you do

using ptr = int* (*) (int*);

you declare an alias named ptr to the type int* (*) (int*).

If you try to do

ptr = &func

you are basically saying

int* (*) (int*) = &func

which as you can see won't work as there is no variable name, just a type.

What you need is

ptr my_ptr = &func;

to create a variable, my_ptr, of type ptr (int* (*) (int*)).

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

1 Comment

Totally makes sense now, i got confused because i saw it being used in private class inheritance and thought this is how its supposed to work

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.