0

I am coming from C# background. There I could do something like this:

Callback callback = new Callback
    {
        src = src,
        callbackPtr = callbackPtr
    };

assuming there is only an empty constructor:

Callback(){}

and both variables are public.

Is there something like that in C++ or do I have to create parameterized constructor here?

3
  • 1
    Could you explain what it means in C#, for those of us who don't know it? Commented Sep 6, 2013 at 22:07
  • BTW That's a fairly new feature in C#, before you had to write Callback callback = new Callback(); callback.src = src; callback.callbackPtr = callbackPtr; ... and that idea works in C++ as well. Commented Sep 6, 2013 at 22:15
  • @KerrekSB It's a default constructor with an intializer for the named members src and callbackPtr. This would be really dangerous in C++. Commented Sep 6, 2013 at 22:53

2 Answers 2

4

If Callback is a plain-old-data (POD) type, you can do this:

Callback callback = {src, callbackPtr};

which uses the structure initialization syntax. It assumes that src and callbackPtr are listed in that order in the class definition.

This works in both C++03 and C++11. In C++11, non-POD classes can use this syntax by defining a constructor that takes a std::initializer_list.

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

1 Comment

In C++11, it can also work for a class with a two-parameter constructor.
0

You can do:

Callback* callback = new Callback
    {
        src,
        callbackPtr
    };

Assuming Callback has fields with the same data types in that order and - big caveat - the fields have to be public.

9 Comments

I am receiving "No matching constructor for initialization" compile error. Even though I defined empty ctor: Callback() {}
This calls a two-argument constructor using the uniform constructor syntax. It is not the same as the C# construct.
but then what's the benefit using that over new Callback(src, callbackPtr); ? I was trying to avoid using parameterized ctor.
There is no benefit aside from uniform notation, unless you are dealing with template code.
This will work if Callback is an aggregate. class vs struct doesn't matter. Having public member variables and no constructor does matter.
|

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.