I'm wondering if it is possible to add methods in main program to an existing class defined in header file.
For example:
There is class CFun
defined in file CFun.hpp
, but in our party.cpp
we want to add a method void hello() {cout << "hello" << endl;};
without editing CFun.hpp
Obviously (unfortunately) construction:
#include "CFun.hpp"
class CFun
{
public:
void hello() {cout << "hello" << endl;};
};
doesn't work returning an error Multiple declaration for 'CFun'
Is it possible to make it work without class inheritance?
No, but you could add a method that takes a reference/pointer to a CFun class - you just won't have access to private data:
void Hello(CFun &fun)
{
cout << "hello" << endl;
}
This is probably the best you'll be able to do. As pointed out by litb - this function has to be in the same namespace as CFun. Fortunately, namespaces, unlike classes, can be added to in multiple places.
You can redefine the class like this:
#define CFun CLessFun
#include "CFun.hpp"
#undef CFun
class CFun : CLessFun
{
public:
void hello() {cout << "hello" << endl;};
};
Put this in a new header file CMoreFun.hpp
and include that instead of CFun.hpp
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With