Pergunta

I've written an abstract class (with pure virtual functions), and I'd like to have a method accept one such class as a parameter. Given that the class is abstract, I understand that I couldn't pass an abstract class to any method, but why can't I pass a subclass of an abstract class to that method? How do I specify that a parameter should be any of the subclasses of a specified baseclass? This is all in C++.

Foi útil?

Solução

You need to specify the parameter as a pointer (or reference), e.g. Abstract * rather than Abstract. If Derived inherits from Abstract, you can pass a variable of type Derived * when Abstract * is expected, but you can't in general pass one of type Derived when Abstract is expected.

Outras dicas

Then you use polymorphism in C++.

Given any base class:

struct Base{};

and its subclasses:

struct SubClassA : public Base(){};
struct SubClassB : public Base(){};

If you declare:

void MyFunctionReference(Base&){};
void MyFunctionPointer(Base*){};

You can then call:

{
   SubClassA a;
   SubClassB b;

   MyFunctionReference(a); // by reference
   MyFunctionPointer(&b); // by pointer address
}

You can indeed do this, observe:

Pure abstract class:

class Abstract {
public:
    virtual void foo() = 0;
};

Child of overrides member function:

class AbstractImpl : public Abstract {
public:
    void foo() override { std::cout << "Hi from subclass\n"; }
};

Now we declare a method that takes a reference type of the abstract class

void somefunc(Abstract &ab) {
    ab.foo();
}

Finally in main we instantiate the child class parameter

int main() {
    AbstractImpl test;
    somefunc(test); // prints Hi from subclass
    return 0;
}

Source: https://stackoverflow.com/a/11422101/2089675

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top