josh
josh

Reputation: 14463

Is it not necessary to define a class member function?

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

Answers (5)

user195488
user195488

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

Philipp
Philipp

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

cpx
cpx

Reputation: 17577

From MSDN Linker Error LNK2019

Upvotes: 1

Johannes Schaub - litb
Johannes Schaub - litb

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

Michael J
Michael J

Reputation: 7949

You can define it elsewhere (like another file)

void Sam::func1()
{
    // do stuff here
}

Upvotes: 2

Related Questions