Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ adding method to class defined in header file

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?

like image 790
Moomin Avatar asked Oct 29 '08 22:10

Moomin


2 Answers

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.

like image 143
Eclipse Avatar answered Oct 13 '22 13:10

Eclipse


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

like image 27
Timo Avatar answered Oct 13 '22 13:10

Timo