Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ abstract class parameter error workaround

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

like image 860
Cemre Mengü Avatar asked Jul 10 '12 21:07

Cemre Mengü


2 Answers

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.

like image 176
Sergey Kalinichenko Avatar answered Sep 23 '22 08:09

Sergey Kalinichenko


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).

like image 27
Luchian Grigore Avatar answered Sep 24 '22 08:09

Luchian Grigore