Cannot call derived class method from vector of base class ptrs

Viewed 7

I am trying to make a vector of different types of derived classes from a base class, which have different implementations of the same method. The vector is of type ptr to base class (Base*) and ptrs provided are of type (Derived*). However, when I try to call the derived method on the elements in the ptr the compiler says the Base class has no method derivedMethod. I have simplified the code to try and explain why I mean. I only have one derived class (whereas the actual code has multiple) but it still doesnt compile:

#include <iostream>
#include <vector> 

/* BASE CLASS */
class Base
{
protected:
    double val;
public:
    Base();
    void baseMethod();
};

Base::Base()
{
    val = 0.0;
}

void Base::baseMethod()
{
    val = 1.0;
}

/* DERIVED CLASS */
class Derived : public Base
{
private:
    
public:
    void derivedMethod();
};

void Derived::derivedMethod()
{
    std::cout << this->val << std::endl;
}

/* ************************************************* */

int main() 
{
    std::vector<Base*> vec;
    
    Derived* dptr = new Derived;
    
    vec.push_back(dptr);
    vec[0]->derivedMethod();
}

This returns the error

error: ‘class Base’ has no member named ‘derivedMethod’
   42 |     vec[0]->derivedMethod();

Is this an example of polymorphism? As in the base class is morphing into different things.

0 Answers
Related