Default User wrote:
Sandy wrote:
I have a code like this
extern "C"
App * GetApp()
{
App a = new App;
a->Init();
return a;
}
Where App is a Class having some data members and accessor/modifier
function.
Is this allowed, i mean can i create an object inside a C function, is there
any ill effect of the code.
Yes and no. Yes, this (with the correction you made in a followup) is
legal C++ code. It is not of course legal C.
If your intention is to call this from a C module, then it won't work.
That's because the C function won't be able to do anything with an
App*. That's the usual reason for this.
The OP may not intend for the C code to do anything with the App*,
except pass it to other C-linkage functions as a "handle". Ferinstance:
APP.H:
// C++ code can just construct and manipulate App objects directly
#ifdef __cplusplus
class App
{
public:
App() {...}
Func1() {...}
Func2() {...}
~App() {...}
};
#endif
// C code can use these functions to access App objects
#ifdef __cplusplus
extern "C" {
#else
struct App;
#endif
App *CreateApp();
void AppFunc1(App *a);
void AppFunc2(App *a);
void DestroyApp(App *a);
#ifdef __cplusplus
}
#endif
APP.CPP:
#include "app.h"
App *CreateApp() {return new App;}
void AppFunc1(App *a) {a->Func1();}
void AppFunc2(App *a) {a->Func2();}
void DestroyApp(App *a) {delete a;}
--
Mike Smith