Using common function in different classes

Jun 28, 2011 at 8:44am
Dear All,

I have a function member f() defined in class c1. How can I use this function by calling it in the body of another class?

Thanks,
B.B.
Jun 28, 2011 at 8:59am
closed account (D80DSL3A)
1) Derive the other classes from c1. The other classes will inherit f() as well as any data members which appear in the function f().

2) Include an instance of c1 as a member of the other classes.
3) Pass a c1 object as an argument to the other classes functions.
4) Use a c1 object as a local variable in the other classes functions.

Whether any of those options are sensible depends entirely upon the problem at hand.
Jun 28, 2011 at 9:07am
Thank you very much,

I could understand the items (1) and (3).

Please, if it is possible, explain more about item (2) and (4).
Jun 28, 2011 at 9:39am
closed account (D80DSL3A)
2) is useful when defining a composite object - something which has parts which are themselves other objects.
Perhaps a fruit object has a seed:
1
2
3
4
5
6
7
#include "seed.h"

class Fruit
{
     seed mySeed;// a seed object is a data member
    // other data and function members, etc...
};

Or a box has a label, which is defined in another class with all the data which a label would contain, a function for printing the label and so on.

For item(4)...? Maybe a function needs a polynomial object for use in a calculation and you have a polynomial class defined.
1
2
3
4
5
6
7
8
9
10
#include "polynomial.h"

class myMathFuncs
{
    float g(float x)
    {
        polynomial P(...);// P is a variable local to the function g()
        // other code
    }
};
Last edited on Jun 28, 2011 at 9:42am
Jun 28, 2011 at 10:45am
Thanks about your explaination....

These are the common ways to include the items of a class in another class. But Is there any way in order to include only one member function of a class without including whole the class by instancing one of its object. I mean is there any way to use "friend" or "virtual" functions just to link the two classes in this matter??

Last edited on Jun 28, 2011 at 10:46am
Jun 28, 2011 at 10:48am
If the function is general enough to be in multiple classes, why is it in a specific class to begin with? Either move it out or make it static (if you really want it to be related to that class)
Jun 28, 2011 at 10:56am
Ok. It is a very good hint. I may find my way to exclude this function or make it static. Now for "static" case, only declaring the base function with identifier "static" is enough?

class c1
{
public:
static void f() { // body of the function // };
};

Then how to use it in another class??
Jun 28, 2011 at 11:02am
1
2
3
4
5
#include "c1.hpp"

class c2 {
   void g() { c1::f(); }
};
Jun 28, 2011 at 11:09am
Ok. Thanks a lot :-)
Topic archived. No new replies allowed.