Reputation: 14463
The following code compiles and runs perfectly,
#include <iostream>
class sam {
public:
void func1();
int func2();
};
int main() {
sam s;
}
Should it not produce a error for the lack of class member definition?
Upvotes: 2
Views: 593
Reputation:
You did define declared it. You just didn't add implementation provided a function prototype. The linker may display a warning if you do not have a function definition (for instance, Borland C++ Builder 5 does not).
Upvotes: 0
Reputation: 49850
If you don't call the member functions, they don't have to be defined. Even if you call them, the compiler won't complain since they could be defined in some other compilation unit. Only the linker will complain. Not defining functions is accepted and common to force an error for undesired behavior (e.g. for preventing copying).
Upvotes: 8
Reputation: 507393
Yes it is perfectly valid to not define a class member function if it is not used. That is also true for non-member functions. A definition is required for virtual functions, though. But pure virtuals can omit definitions if they aren't used.
"Used", btw, does not include refering to the function within sizeof
. In other words, this is still valid:
sizeof (s.func2()); // still not used!
Upvotes: 4
Reputation: 7949
You can define it elsewhere (like another file)
void Sam::func1()
{
// do stuff here
}
Upvotes: 2