Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to define a class in 2 or more file in C++?

I know it's possible to do class implementation in more than one file(yes, I know that this is bad idea), but I want to know if it's possible to write class definition in separate files without getting a redefinition error (maybe some tricks, or else...)

like image 604
Mircea Ispas Avatar asked Dec 22 '22 19:12

Mircea Ispas


1 Answers

No, not the same class, but why would you?

You could define two classes with the same name in the same namespace (the same signature! That will actually be the same class at all, just defined in two ways) in two different header files and compile your program, if your source files don't include both headers. Your application could even be linked, but then at runtime things won't work as you expect (it'll be undefined behavior!), unless the classes are identical.

See Charles Bailey's answer for a more formal explanation.


EDIT:

If what you want is to have a single class defined by more than one file, in order to (for example) add some automatically generated functions to your class, you could #include a secondary file in the middle of your class.

/* automatically generated file - autofile.gen.h */
void f1( ) { /* ... */ }
void f2( ) { /* ... */ }
void f3( ) { /* ... */ }
/* ... */

/* your header file with your class to be expanded */
class C
{
    /* ... */
    #include "autofile.gen.h"
    /* ... */
};
like image 163
peoro Avatar answered Jan 09 '23 12:01

peoro