0

I have code which is structured similar to the following:

#include <iostream>

class base
{
    public:
        void method();
};

class A:public base
{
public:
    void method();
};

void base::method()
{
    std::cout << "base method\n";
}

void A::method()
{
    std::cout << "A method\n";
}


int main()
{
base* array[1];
array[0] = new A;

array[0]->method(); //should call A::method() but it doesnt.

delete array[0];


}

I would like to, whenever i call "method()" using the pointer array call the method belonging to the A class (or any other classes derived from base, pointed to by array[]).

However this code seems to always call the method attached to the class "base". From what I understand the "method()" defined by the class A should override the "method()" in the base class.

How do i call the method defined in "A" via an array of pointers of type "base"?

Thanks for any help.

1 Answer 1

4

You need to declare method() as virtual in order to get this to work.

Without the virtual keyword, the compiler will statically, at compile time, choose to call the method associated with the pointer (or reference) type, as opposed to the object type that the pointer is pointing to.

By declaring the method as virtual, you're instruction the compiler to instead make the selection of which function to call at runtime and call the function not based on the type of the pointer, but the type of the object the pointer is pointing to.

Sign up to request clarification or add additional context in comments.

1 Comment

and the destructors as well

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.