4

This simple code produces some unexpected results. At least for me...

#include <iostream>
class cls1
{
public:
    cls1(){std::cout << "cls1()" << std::endl;};
    cls1(int, int) : cls1() {std::cout << "cls1(int, int)" << std::endl;}
};

class cls2 : public cls1
{
public:
    using cls1::cls1;
    cls2() = delete;
};

int main()
{
    cls2 c();
    return 0;
}

I would expect an output to be: cls1() as the default constructor is deleted for cls2, but the code does not output anything, though it compiles and runs fine. I am using GCC ver. 4.8.2. Compile with:

$ g++ -std=c++11 -g test.cpp

$ ./a.out

The question is: how should it behave?

Thank you!

  • possible duplicate of [Default constructor with empty brackets](http://stackoverflow.com/questions/180172/default-constructor-with-empty-brackets) – Casey Feb 14 '14 at 18:48

1 Answers1

2

You're not actually creating an instance of cls2 in your main(); you're declaring a function that returns a cls2. This is an instance of the "most vexing parse". See, for example, http://en.wikipedia.org/wiki/Most_vexing_parse

Adam H. Peterson
  • 4,511
  • 20
  • 28
  • Then how does it build/link since there is no cls2 c() { .. ? – paulm Feb 14 '14 at 18:42
  • 1
    @paulm You declare the function but do not use it, so no definition is necessary. – Casey Feb 14 '14 at 18:45
  • Thank you for the answer! I should've used braces init syntax to avoid this situation: cls2 c{}; – Dmitriy Shvidchenko Feb 14 '14 at 19:26
  • @user3311348, yes, this is a good workaround for the most vexing parse. I expect if you do, you'll find that your test program will fail to compile because it's trying to call a deleted constructor. (I don't have GCC 4.8, though, so I can't test it now.) – Adam H. Peterson Feb 14 '14 at 19:33
  • Adam, that what i tested before putting my comment. The output: `test.cpp: In function ‘int main()’: test.cpp:37:9: error: use of deleted function ‘cls2::cls2()’ cls2 c{}; ^ test.cpp:31:2: error: declared here cls2() = delete; ^` – Dmitriy Shvidchenko Feb 14 '14 at 19:42