1

In the following code, I have two parametrizes constructors. I have compiled and run into Gcc compiler but constructors not called.

#include <iostream>

class A 
{
  public:
  A(int i) 
  { 
      std::cout << "A constructed" << std::endl; 
  }
};

class B 
{
  public:
  B(A a1) 
  { 
      std::cout << "B constructed" << std::endl; 
  }
};

int main() 
{
  int i = 5;
  B b1(A(i));
  std::cout << i << std::endl;
  return 0;
}

Output:

5

So, Why constructors not called?

Nicol Bolas
  • 449,505
  • 63
  • 781
  • 982
Jayesh
  • 4,755
  • 9
  • 32
  • 62
  • I assume the compiler optimises the construction of the objects away, since they are not used anymore afterwards. – Rene Oct 02 '17 at 06:26
  • 2
    Both constructor are actually `private`, so you cannot call then. According to clang (I would not have found it myself), you are facing the [Most vexing parse](https://en.wikipedia.org/wiki/Most_vexing_parse) - `B b1(A(i))` is not constructing a variable `b1`, but declaring a function. The `i` that you use in `B b1(A(i))` is not the `i` you declared a line before (try removing it, the code will still compile). – Holt Oct 02 '17 at 06:27
  • @StoryTeller I do agree that these duplicates are (very closely) related, but I found the syntactic ambiguity here much more *vexing* than the ones in the provided links - I am well aware of the most vexing parse, but I would not have detected it here without clang's warning, maybe it is worth having a specific answer for this question (or maybe a canonical one elsewhere). – Holt Oct 02 '17 at 06:35
  • @Holt - I did answer a similar question once, wher `T(foo)` declared a parameter name `foo`. So this is still a dupe. I'm just looking – StoryTeller - Unslander Monica Oct 02 '17 at 06:37
  • 1
    @StoryTeller Maybe this one https://stackoverflow.com/questions/38951362/most-vexing-parse (or the duplicate target). – Holt Oct 02 '17 at 06:39
  • 1
    @Holt - Edited both in. I don't think there's a facet of the most vexing parse that isn't covered by the linked dupes anymore. – StoryTeller - Unslander Monica Oct 02 '17 at 06:41

1 Answers1

-4

Your both constructors are defined under private. Private constructors are not visible to the objects and thus cannot be called.

Ryan
  • 1
  • 4