Reputation: 469
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!
Upvotes: 0
Views: 146
Reputation: 238351
You cannot indirect through a pointer to void
. And there is no need for a pointer to void
.
The simplest solution is this:
int number = 1;
std::cout << input
? obj.alpha.object_method(number)
: obj.beta.object_method(number);
For the edited question: The above still works, but you can get rid of the repetition of the complex code using a function template. Here is an example using a lambda:
auto do_stuff = [](auto& either_A_or_B) {
for(int i = 0; i < either_A_or_B.object_method(); i++)
{
std::cout << i << std::endl;
}
};
input
? do_stuff(obj.alpha)
: do_stuff(obj.beta);
P.S. Avoid using C-style casts.
Upvotes: 4
Reputation: 10756
This is not a good use for void*
and if, like you comment, you can't make use of inheritance and the actual problem is more than just console output, then you could still make it generic with a function template
template <class T>
void according_to_user_input(T &obj)
{
std::cout << obj.object_method();
}
and use it like so
if (input)
according_to_user_input<Object_A>(W.alpha);
else
according_to_user_input<Object_B>(W.beta);
Upvotes: 2