1

I have a C++ code that seems to be confusing a class contructor like A::A(B b) with a constructor that receives a function pointer, like A::A(B (*)()). Let me explain:

The following code compiles:

#include <iostream>
#include <cstring>
#include <vector>

struct Item {
  Item() {
    std::cout << "ITEM::Normal constructor\n";
  }
};

struct Container {
  Container(Item i) {
    std::cout << "CONTAINER::Normal constructor\n";
  }

  void doSomething() {
    std::cout << "Do something\n";
  }
};

int main() {
  Container c3(Item());
  return 0; 
}

But if I add a call to B::doSomething(), like the following code, I obtain a compiler error that I don't understand:

#include <iostream>
#include <cstring>
#include <vector>

struct Item {
  Item() {
    std::cout << "ITEM::Normal constructor\n";
  }
};

struct Container {
  Container(Item i) {
    std::cout << "CONTAINER::Normal constructor\n";
  }

  void doSomething() {
    std::cout << "Do something\n";
  }
};

int main() {
  Container c3(Item());
  c3.doSomething();
  return 0; 
}

The compiling error is:

main.cpp: In function ‘int main()’:
main.cpp:23:6: error: request for member ‘doSomething’ in ‘c3’, which is of non-class type ‘Container(Item (*)())’
   c3.doSomething();
Dan
  • 2,452
  • 20
  • 45

1 Answers1

2

It's a veiled most vexing parse issue:

Container c3(Item());

declares a function prototype, and your helpful compiler issues the appropriate diagnostic.

Container c3{Item()};

is the fix.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483