Reputation: 465
I have a function that I want to use in different classes. Is this possible?
Example:
int getNumber()
{
// do something here that will use some values like:
int number = num * pi;
return number;
}
class Human
{
int num;
// other member
int getNumber(); // same as above
}
class Robot
{
int num;
// other member
int getNumber(); // same as above
}
The getNumber()
function can be short as return num;
or long depends on the computation that will happen inside the function.
The num
value inside the getNumber()
is the num
member of both Human
and Robot
class. Although, these classes do not have the parent-child or friend relationship.
Upvotes: 2
Views: 157
Reputation: 299760
It is certainly easy. Although there is no sweet syntax for delegation in C++ (a shame, this has brought so many abuses of inheritance...).
1. The free-function way
int transformNumber(int num) { return num * pi; }
class Human {
public:
int getNumber() const { return transformNumber(num); }
private:
int num;
};
2. The composition way
struct NumberThing {
int num;
int getNumber() { return num * pi; }
};
class Human {
public:
int getNumber() { thing.getNumber(); }
private:
NumberThing thing;
};
Pick your favorite.
Upvotes: 3
Reputation: 113866
This is a good instance to use inheritance. Both objects have stuff in common often mean that they are really subclasses of a more general class:
class Being
{
int num;
int getNumber() {/* .. */}
}
class Robot: public Being
{
}
class Human: public Being
{
}
Upvotes: -1
Reputation: 3141
Make a class that has this function and extend other classes that uses that functionality.
Upvotes: 0