The code snippet below produces an error:
#include <iostream>
using namespace std;
class A
{
public:
virtual void print() = 0;
};
void test(A x) // ERROR: Abstract class cannot be a parameter type
{
cout << "Hello" << endl;
}
Is there a solution/workaround for this error other/better than replacing
virtual void print() = 0;
with
virtual void print() = { }
EDIT: I want to be able to pass any class extending/implementing the base class A as parameter by using polymorphism (i.e. A* x = new B() ; test(x);
)
Cheers
Since you cannot instantiate an abstract class, passing one by value is almost certainly an error; you need to pass it by pointer or by reference:
void test(A& x) ...
or
void test(A* x) ...
Passing by value will result in object slicing, with is nearly guaranteed to have unexpected (in a bad way) consequences, so the compiler flags it as an error.
Of course, change the signature:
void test(A& x)
//or
void test(const A& x)
//or
void test(A* x)
The reason your version doesn't work is because an object of type A
doesn't logically make sense. It's abstract. Passing a reference or pointer goes around this because the actual type passed as parameter is not A
, but an implementing class of A
(derived concrete class).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With