views:

1704

answers:

6

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?

A: 

Not to my knowledge. Although, you could do some kind of jury-rigging and make a namespace-y solution.

Paul Nathan
+5  A: 

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.

Eclipse
you should tell him the function needs to be in the same namespace like the class. otherwise just calling Hello(some_cfun); won't find the Hello. you would have to write foo::Hello(some_cfun); then (ADT won't work then)
Johannes Schaub - litb
+1  A: 

No, that is not possible. There can only be one definition of any particular class, and it has to be a complete definition, meaning that you cannot have partial definitions in different places, adding members to the class.

If you need to add a member function to a class, then either you have to change the class definition (edit CFun.hpp), or derive a new class from CFun and put hello() there.

Dima
A: 

After thinking about it, you could do something terrible: Find some function in CFun that has a return type that you want, and is only mention once in the entire header. Let's say void GoodBye().

Now create a file CFunWrapper.hpp with this content:

#define GoodBye() Hello() { cout << "hello" << endl; } void GoodBye()
#include "CFun.hpp"
#undef GoodBye

Then only ever include CFunWrapper.hpp instead of CFun.hpp.

But don't do this, unless there's some really good reason to do so. It's extremely prone to breaking, and may not even be possible, depending on the contents of CFun.hpp.

Eclipse
Doing this is the same as just modifying CFun.hpp. It's pretty difficult to think of a situation where this will work, but you can't just change the header file. I guess it could be on a ROFS.
Steve Jessop
A: 

The closest analog to that sort of construct (adding functionality to predefined classes) in C++ is the Decorator pattern. It's not exactly what you're after, but it may allow you to do what you need.

Harper Shelby
A: 
class Party : class CFun

(your party.cpp)

inherits CFun stuff, including hello() function.

So...

Party p;
p.hello();

No?