How to call virtual function of an object in C++
        Posted  
        
            by 
                SoonDead
            
        on Stack Overflow
        
        See other posts from Stack Overflow
        
            or by SoonDead
        
        
        
        Published on 2012-11-10T16:55:07Z
        Indexed on 
            2012/11/10
            16:59 UTC
        
        
        Read the original article
        Hit count: 244
        
I'm struggling with calling a virtual function in C++.
I'm not experienced in C++, I mainly use C# and Java so I might have some delusions, but bear with me.
I have to write a program where I have to avoid dynamic memory allocation if possible. I have made a class called List:
template <class T> class List {
public:
    T items[maxListLength];
    int length;
    List() {
        length = 0;
    }
    T get(int i) const {
        if (i >= 0 && i < length) {
            return items[i];
        } else {
            throw "Out of range!";
        }
    };
    // set the value of an already existing element
    void set(int i, T p) {
        if (i >= 0 && i < length) {
            items[i] = p;
        } else {
            throw "Out of range!";
        }
    }
    // returns the index of the element
    int add(T p) {
        if (length >= maxListLength) {
            throw "Too many points!";
        }
        items[length] = p;
        return length++;
    }
    // removes and returns the last element;
    T pop() {
        if (length > 0) {
            return items[--length];
        } else {
            throw "There is no element to remove!";
        }
    }
};
It just makes an array of the given type, and manages the length of it.
There is no need for dynamic memory allocation, I can just write:
List<Object> objects;
MyObject obj;
objects.add(obj);
MyObject inherits form Object. Object has a virtual function which is supposed to be overridden in MyObject:
struct Object {
    virtual float method(const Input& input) {
        return 0.0f;
    }
};
struct MyObject: public Object {
    virtual float method(const Input& input) {
        return 1.0f;
    }
};
I get the elements as:
objects.get(0).method(asdf);
The problem is that even though the first element is a MyObject, the Object's method function is called. I'm guessing there is something wrong with storing the object in an array of Objects without dynamically allocating memory for the MyObject, but I'm not sure.
Is there a way to call MyObject's method function? How? It's supposed to be a heterogeneous collection btw, so that's why the inheritance is there in the first place.
If there is no way to call the MyObject's method function, then how should I make my list in the first place?
© Stack Overflow or respective owner