Reputation: 4988
I have a situation: In a single Solution I have two Projects. I need to extend the Class:Foo used in Project:A so that I can add new functionality required in Project:B without changing its name. Problem is: Class:Foo already contains (i.e. has a) Class:Bar and is contained by Class:Goo in both Project:A & Project:B. In Project:B I am inheriting Class:Goo into Class:Goo_Ex; but I need to also extend both: Class:Foo and Class:Bar with companion functions.
To make it more clear - I could accomplish this using the following crude method:
/* Project:A-Class:Foo */
class Foo
{
.
.
.
# ifdef PROJECT_B
fnExtended();
# endif
};
but that would litter my code in Project:A.
A possible solution that I can think of is to use Inheritance and have Class:Foo_Global Inherited-[Only] as Class:Foo in Project:A and Inherited-[Extend] as, again, Class:Foo in Project:B; same for Class:Bar. But is their a more straight forward solution..?
Upvotes: 0
Views: 292
Reputation: 153840
The way to extend you class is not to extend it! Just use a function taking suitable arguments instead.
Upvotes: 0
Reputation: 56048
This is a really abstract problem, and it's difficult to give you a good specific solution without more details.
The basic way of handling this is inheritance. But this requires some pre-planning. It means that when you refer to Foo in project A, you should use pointers or references. If you create a Foo (and need code from project A create Foo_Extended when it's part of project B) then you need to have a configurable Foo factory that will create objects of the appropriate type depending upon context.
The other way of handling this is templates. You never have the code in project A refer directly to the global Foo class. Instead it always refers to a template parameter. In project A that template parameter will end up resolving to Foo, and in project B it will resolve to some other class that has the needed functionality.
These are the two general ways of handling this issue in C++. And which you use depends a lot on the details of the context in which you're using them.
Upvotes: 0
Reputation: 249183
I think your proposed solution (to hide the current Foo as some other class name and inherit from it in a new Foo class in both projects) is how you should do it.
Upvotes: 1