1

I encountered some strange behavior of the paramterless constructor in C++, which I do not understand:

The line myClass c; calls the parameterless constructor, the line myClass c(); doesn't. Why does this happen? And what gets called when I use c()?

An example, where this occurs:

//myClass.h

class myClass{
public:
   myClass();
   myClass(int x);
}

//myClass.cpp

#include "myClass.h"
#include <iostream>

myClass::myClass(){
   std::cout << "Class created." << std::endl;
}
myClass::myClass(int x){
   std::cout << "Class created with value " << x << std::endl;
}

The main function:

#include "myClass.h"

int main()
{
    myFancyClass c1;//paramterless contructor gets called
    myFancyClass c2();//something I do not understand happens
    myFancyClass c3(2);//int contructor gets called
}

The output is:

Class created
Class created with value 2

So again: why does this happen? And what does actually happen when I call c2()?

  • 2
    This is known as [the most vexing parse in C++](https://en.wikipedia.org/wiki/Most_vexing_parse). – R Sahu Mar 30 '20 at 04:57

0 Answers0