2

I want a function that receives a vector with elements of the base class and executes the method of the corresponding inherited class. I don't know if I should define a virtual function in the base class. Anyway it can't be a pure virtual function as long as I don't want the inherited classes to be abstract.

class A {
public:
    void printSubclass() {
        std::cout << "No subclass found";
    }
};

class B : public A {
public:
    void printSubclass() {
        std::cout << "Subclass B";
    }
};

class C : public A {
public:
    void printSubclass() {
        std::cout << "Subclass C";
    }
};

void function(vector<A> MyVec) {
    for(int k=0; k<Myvec.size(); k++)
        MyVec[k].printSubclass();
}

int main() {
    B ObjB;
    C ObjC;
    vector<A> MyVector= {ObjB, ObjC}    
    function(ObjB);
    return 0;
}
  • Does this answer your question? [Why do we need virtual functions in C++?](https://stackoverflow.com/questions/2391679/why-do-we-need-virtual-functions-in-c) – Kane Oct 31 '19 at 15:43
  • You also have to read [this](https://stackoverflow.com/questions/274626/what-is-object-slicing) and [this](https://stackoverflow.com/questions/15188894/why-doesnt-polymorphism-work-without-pointers-references/30966096) – n. m. could be an AI Oct 31 '19 at 18:25

1 Answers1

1

You will need to make printSubclassvirtual (whether pure or not would depend on whether actual objects of 'A' make sense rather than on anything to do with the derived classes). And tregardless of whether printSubclass is pure the vector will need to be of A* rather than A objects directly. With the vector holding 'A' objects whenever you put non-A objects into the vector the non-A portions get sliced off.

SoronelHaetir
  • 14,104
  • 1
  • 12
  • 23