Given the following piece of code as a minimum working example:
#include <iostream>
class Object_A
{
public:
int attribute_a,attribute_b;
Object_A(int a,int b){
this->attribute_a = a;
this->attribute_b = b;
}
int object_method(){
std::cout << "Hello from Object A: " << std::endl;
return (this->a + this->b);
}
};
class Object_B
{
public:
int attribute_c, attribute_d;
Object_B(int c,int d){
this->attribute_c = c;
this->attribute_d = d;
}
int object_method(){
std::cout << "Hello from Object B" << std::endl;
return (this->c + this->d);
}
};
class Object_Omega
{
public:
Object_A alpha;
Object_B beta;
Object_Omega (Object_A first, Object_B second):
alpha(first),
beta(second)
{}
int foobar(int a){ return a; }
};
void according_to_user_input(bool input,Object_Omega obj)
{
void * either_A_or_B;
if (input){ either_A_or_B = & obj.alpha; }
else { either_A_or_B = & obj.beta; }
/* problem here */
for(int i = 0; i < either_A_or_B->object_method(); i++)
{
std::cout << i << std::endl;
}
}
int main()
{
/* this happens somewhere */
Object_A new_A = Object_A(1,2);
Object_B new_B = Object_B(3,4);
Object_Omega W = Object_Omega(new_A, new_B);
according_to_user_input(true/*false*/, W);
return 0;
}
I wish to use a void
pointer (e.g., inside the function according_to_user_input
) but I am struggling to comprehend the proper way to do this. Similar questions have been asked [1], [2] but I did not manage to make this work in the case of the values being pointed towards from the pointer being custom objects.
Given the user input I wish to invoke the object_method()
either from A
or from B
through the Omega
object. Unfortunately the code that I've been working on has this showcased behavior as is and not as an inheritance relationship between the objects in order to avoid the ugly void
C-like and definitely not C++ -like scenario.
Thank you in advance!