Reputation: 103
I have a problem about explicit functions in implementation and interface files is C++. Let me explain it with an example.
The interface file:
#ifndef IntCell_H
#define IntCell_H
class IntCell{
public:
explicit IntCell(int initialValue =0);
int read() const;
void write( int x );
private:
int storedValue;
};
#endif
The implementation file:
#include "IntCell3.h"
IntCell::IntCell(int initialValue)
:storedValue(initialValue) {}
int IntCell::read() const
{ return storedValue; }
void IntCell::write( int x )
{ storedValue = x ;}
While writing these codes, signatures must match exactly as we can see in the read function ( both are accessors ). I am OK with that but the question is why I cannot write
IntCell::explicit IntCell(int initialValue)
in the implementation file? What is the reason that I cannot add the word "explicit" to this line? Thanks in advance.
Upvotes: 1
Views: 153
Reputation: 3145
The reason is that explicit needs not be matched against. It forbids a certain behavior which leads into only one version of the method.
Header files are used to communicate the interface. Before template days it was common to have shipped only header and the library files. The implementation was hidden.
If what you suggest was possible, it would be also possible to redefine the constructor as not explicit in another compilation unit, and that would not allow the intended behavior , which is to restrict the construction by implicit conversions.
You cannot define constructors explicit and not explicit. Because the moment you would define the latter, the former would become invalid.
For example
explicit constructor( int );
constructor( int )
This is invalid, because the compiler would be possible to perfor implicit conversions from the second. Therefore the first would be nonsensical.
In contrast with const functions you can provide two prototypes without any issues because the compiler can pickup the case that your object is const accessed and use the const version, whereas in the other case it will use the non const. The two cases are non intersecting.
void myfun() const;
void myfun();
Is valid code.
Upvotes: 0
Reputation: 56567
Because those are the rules. You put explicit
only in the declaration (header). The reason is because the implementation is visible in other translation units only via the declaration. So if the declaration is not marked explicit
in the header, then other translation units cannot "know" that the function is marked explicit
. And because putting explicit
does not make sense in the implementation file, the designers of the language decided that it should only be used in the declaration. Another reason is clarity: why adding another useless notational syntax to a language that allow declarations that are already complicated enough, like:
void (*signal(int, void (*fp)(int)))(int);
Upvotes: 3