-3

Creating a Foo object passing func to constructor works just fine in this example:

int func(int a) { return a; }

struct Foo {
  Foo( int (*func_ptr)(int) ) {};
};

Foo bar(func);

However attempting to create a Foo object inside another class does not:

class ThisIsCrap {
  Foo doesntWork(func);
};

How can I create a Foo object inside a class like I can outside a class? On the bit that doesn't compile, the error is: "cannot resolve type 'func'"

Thanks in advance.

2 Answers2

0

1,000 thanks to Kerrek SB.

class ThisWorks {
    Foo* working;
    ThisWorks() {
         working = new Foo(func);
    }
}
0

You can provide an initializer for non-static class data members with a default member initializer (DMI):

int func(int a) { return a; }
struct Foo { Foo(int (*)(int)) {}; };

class ThisIsGreat {
  Foo one_way = func;     // DMI with copy-initialization syntax
  Foo another_way{func};  // DMI with list-initialization syntax
};

Or of course you could use a constructor:

class ThisIsSane {
  ThisIsSane()
      : third_way(func)   // constructor-initializer list
  {}

  Foo third_way;
};

Language-lawyer note for pedants: In C++11, ThisIsGreat is not an aggregate; in C++14 it is.

Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
  • I knew that could be done with basic data types, but for whatever reason my brain seized up and didnt connect the dots to abstract data types as well. Well.. I am embarrassed to say the least lol, I need to put the coffee away, fold the laptop, and go to sleep. Maybe when I wake up later I will have regained some IQ points.... and my dignity. @Kerrek, again, Thanks! – Bryan Fallin Mar 15 '17 at 10:20
  • As I said, always reduce your problem to the absolute core of the question, and just by doing so you would probably discover the missing link. – Kerrek SB Mar 15 '17 at 10:21