Declaration and declaration with a definition. Why is this not allowed?

I wonder why it’s not allowed to write:

struct foo { void bar(); // declaration void bar(){std::cout << "moo" << std::endl;} // declaration + definition }; 

The function is declared twice (I thought it was normal) and defined once. However, my compiler complains:

 decldef.cxx:7:10: error: 'void foo::bar()' cannot be overloaded 

Why is this not allowed?

Why does my compiler (g ++ 4.7.2) interpret this as an overload?

PS: I know how to write the β€œright way”, but I just wanted to know why this is wrong.

+5
source share
2 answers

From Β§9.3

With the exception of the definitions of member functions that appear outside the class definition and with the exception of explicit specializations of member functions of class templates and member function templates (14.7) that go beyond the class definition, the member function should not be updated .

In addition, in this case, statements may also fall:

A member function can be defined (8.4) in a class definition, in which case it is a built-in member function (7.1.2), or it can be defined outside its class definition if it has already been declared but not defined in its definition class.

Since the first declaration does not declare the inline function. The second definition implicitly does.

However, this reflex seems less convincing.

+10
source

The function is declared twice (I thought it was normal) and defined once.

It does not depend on whether you define the function a second time. The fact is that you declare this function twice, and this is not normal.

This also does not compile with the same error message:

 struct foo { void bar(); void bar(); }; 

You cannot re-declare the same function with the same list of parameters inside the class definition:

 'void foo::bar()' cannot be overloaded with 'void foo::bar()'. 
+5
source

Source: https://habr.com/ru/post/1241398/


All Articles