Hi! I am writing a program and recent encountered a problem with the concept of "abstract class". In a simplified form, my problem is: I have a function f(x), where x can be either of class A1 or class A2. As f requires specific member methods of in A1 and A2, I really don't want to use template (which looks like everything can be inserted there). I choose to use a common base class instead. (After all, in reality, A1, A2 are really two types of a thing). More precisely:
class A
{
public:
virtualvoid say(){};
};
void f (A X) {X.say();};
class A1: A
{
public:
void say(){std::cout<<"Meow"<<std::endl;};
};
class A2: A
{
public:
void say(){std::cout<<"Geow"<<std::endl;};
};
int main()
{
A1 X1; A2 X2;
f(X1);
f(X2);
return 0;
};
This works just fine and load the proper function. However as class A does not do anything in A::say(), it is some sort of "virtual class" to serve as argument for f. To prevent any usage of this class A, I try to make it abstract by setting virtual say() = 0;. But this does not compile because the compiler complains that A::say() was not implemented.
My question is: how to prevent any real usage of A then? Or template is the preferred solution after all? Other question: is there also computational cost in overloading virtual functions in comparison to using templates?
you simply have to make the parameter of f a pointer to an A
when writing f(A) you say that the function will get an Instance of A which is not possible because it has a pure virtual method
// Example program
#include <iostream>
#include <string>
class A
{
public:
virtualvoid say() = 0; // = 0 marks pure virtual methods
};
void f (A* X) {X->say();};
class A1 : public A
{
public:
void say(){std::cout<<"Meow"<<std::endl;};
};
class A2 : public A
{
public:
void say(){std::cout<<"Geow"<<std::endl;};
};
int main()
{
A1 X1; A2 X2;
f(&X1);
f(&X2);
return 0;
}
some sort of "virtual class" to serve as argument for f
something like this is called an interface, I just want to clear the terminology
an interface is a class with only pure virtual methods
an abstract class is a class with at least one pure virtual and at least one implemented method
(if someone knows better please correct me)
Thank you both. It indeed works for that minimal example. Somehow it still does not work for my bigger program.
./src/vsystem.cpp:26:24: warning: inline function 'virtual double vsystem::getTEntropy() const' used but never defined
virtual inline double getTEntropy() const = 0;
But maybe it is just another problem. I am trying to fix.