Cannot call derived class method from vector of base class ptrs

Issue

This Content is from Stack Overflow. Question asked by Will Denny

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.



Solution

This question is not yet answered, be the first one who answer using the comment. Later the confirmed answer will be published as the solution.

This Question and Answer are collected from stackoverflow and tested by JTuto community, is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?