Passing Class Objects Into Another Class Object Without Knowledge of the Passed Object

I have the following situation:

I have 2 classes that are not related to each other. Call these ClassA and ClassB.

I have another class. Call it Class1.

Class1 has methods that operate on data members from the other 2 classes. In particular, Class1's methods operate on data members from only one of the 2 classes. (For example, Class1 will operate on ClassA's data members or ClassB's data members, but not both at the same time. ClassA and ClassB have data members with the same names.) In the scenario where I know which of the 2 classes is being operated on, then this would be a fairly simple problem. (For example, if I knew that I was going to operate on data members from ClassA in Class1, then I would pass in a reference to an object of ClassA within the methods of Class1). However, in my actual scenario, I am required to not know which of the 2 classes is being operated on in Class1's methods. I have searched online for what to do here, but I am lost. I don't even really know what to call this kind of situation. How can this be accomplished? Thanks!
Last edited on
You can have ClassA and ClassB derive from some parent object and pass in a reference to the parent object to Class1's methods.
Actually, in my real scenario, ClassA and ClassB are child objects of different parents. So, I don't think that solution is going to work. Is there another way around this?
You can make Class1's methods template methods.
I don't know much about template methods. I only recently learned how to write template functions and classes, so I'm still not totally confident in using them. Could you provide an example? Or maybe it would be easier to just create a new parent class? (I could just scratch the current parent classes of ClassA and ClassB such that ClassA and ClassB will now be derived from a new, single parent class.)
Example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
class ClassA
{
public:
   void Member()
   {
   }
};

class ClassB
{
public:
   void Member()
   {
   }
};

class Class1
{
public:
   template <class T>
   void Class1Method(T& t)
   {
      t.Member();
   }
};

int main()
{
   ClassA a;
   ClassB b;

   Class1 class1;
   class1.Class1Method<ClassA>(a);
   class1.Class1Method<ClassB>(b);

   return 0;
}
Awesome! Thank you!
Topic archived. No new replies allowed.