user2670891
user2670891

Reputation: 41

Different class objects passing C++

well i have some predefined classes

class x
{
   int y;
} xx;
class z
{
  int y;
} zebra;

and i want to pass xx or zebra depending on few conditions to a function

function(x xx) or function(z zebra)

as the functionality of "function" is same for both above, how can i write a single function which can take both xx and zebra. I am not allowed to redefine or declare the classes

Upvotes: 0

Views: 90

Answers (2)

Zdeněk Jelínek
Zdeněk Jelínek

Reputation: 2923

If you need something like

void add3(x xx)
{
    xx.y += 3;
}

to be usable for class z, you would be best off using template function:

template<typename T>
void add3(T value)
{
    value.y += 3;
}

Another option would be just to use overloading and define two functions:

void add3(x xx)
{
    xx.y += 3;
}

void add3(z zebra)
{
    zebra.y += 3;
}

Overloading may be better idea in case when the two classes x and z should differ in abstraction.

In case when their abstraction is the same, they should be based on shared interface (e.g. base with y field and both x, z should inherit base and then you'd only have void add3(base b)). You can see example of this in std::ios (http://www.cplusplus.com/reference/ios/) where inputs and outputs (std::istream, std::ostream) are both streams, yet they provide quite different functionality when it comes to actual usage.

On the other hand, lots of STL containers do not have this interface pattern, so the template solution is not always a bad idea. It's just a matter of your style and the resources you are using.

Upvotes: 3

flogram_dev
flogram_dev

Reputation: 42868

It depends on what you need to do inside function.

If both x and z can be handled with the same code inside function, make function a template function.

Otherwise make two overloads for function, one taking an x and one taking a z.

Upvotes: 2

Related Questions