Is there a way to use an existing function as a part of a class? If yes, how?

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.

Answers


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.


Make a class that has this function and extend other classes that uses that functionality.


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
{

}

Need Your Help

Is there a way to use an existing function as a part of a class? If yes, how?

c++ function class

I have a function that I want to use in different classes. Is this possible?

What's the definition of 'heavy threading environment'?

multithreading environment

I'm using a lock over a section of code. Although the critical section is small, many threads would reach there (about 100 threads per second). In some articles I see this method is not suitable for

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.