Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I wonder, why it is 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 this is ok) and defined once. However, my compiler complains about:

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

Why is it not allowed?

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

PS: I know how to write it "the correct way", but I just would like to know, why the above is wrong.

like image 275
463035818_is_not_a_number Avatar asked Jan 25 '16 09:01

463035818_is_not_a_number


1 Answers

From §9.3

Except for member function definitions that appear outside of a class definition, and except for explicit specializations of member functions of class templates and member function templates (14.7) appearing outside of the class definition, a member function shall not be redeclared.

In addition, in this case the statements may also fall foul of:

A member function may be defined (8.4) in its class definition, in which case it is an inline member function (7.1.2), or it may be defined outside of its class definition if it has already been declared but not defined in its class definition.

As the first declaration does not declare the function to be inline. The second definition implicitly does.

However, that one on reflection seems less convincing.

like image 98
Richard Hodges Avatar answered Sep 28 '22 13:09

Richard Hodges