Jump to content
  • Advertisement
Sign in to follow this  
greeb

C++ Overriding member functions and vectors.

This topic is 3452 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hi all, my first post here so I hope this is in the right sort of area. I've run into a problem while experimenting with inheritance in a small, text based game I'm working on. Here's some similar code that I put together to show the problem:
#include <iostream>
#include <vector>

using namespace std;

class Base
{
      public:
             Base(int a, int b);
             virtual int calculate();
             int a;
             int b;
};

Base::Base(int a, int b):
               a(a),
               b(b)
               {}
               
int Base::calculate()
{
    return (a+b);
}

class Derived: public Base
{
      public:
             Derived(int a, int b);
             int calculate();
};

Derived::Derived(int a, int b):
                     Base(a,b)
                     {}

int Derived::calculate()
{
    return (a*b);
}


int main()
{
    Base base(5,5);
    Derived derived(5,5);
    
    // This works.
    Base* p_base = &base;
    Base* p_derived = &derived;
    
    vector<Base*> p_vec;
    p_vec.push_back(p_base);
    p_vec.push_back(p_derived);
    
    for (int i = 0; i != p_vec.size(); ++i)
    {
        cout << p_vec->calculate() << endl;
    }
    
    // This doesn't.
    vector<Base> vec;
    vec.push_back(base);
    vec.push_back(derived);
    
    vector<Base>::iterator iter;
    for (iter = vec.begin(); iter != vec.end(); ++iter)
    {
        cout << iter->calculate();
        cout << endl;
    }
    
    return 0;
}

Basically, when using an iterator to go through the vector, the base class member function is called each time, and the function is not overrided by the new calculate() function I defined in the derived class. As you can see, I can get the results I want by using a vector of pointers, but I'm curious as to why the second method doesn't work. I can only assume that it's something to do with the vector being declared as containing <Base> objects? Any workaround to this, or is it best to just stick to the first method?

Share this post


Link to post
Share on other sites
Advertisement
Your issue is called slicing. When you store a polymorphic base class by value and copy a derived class to that base, you only copy the base class parts, not the derived class parts. Basically, you need to store (smart) pointers in order to get polymorphism to work.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!