Virtual function not behaving like it should

Hi, not sure I did well posting here instead of the Beginners' subforum. Oh well.

Long story short, I have these two classes:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Motion
{
    protected : 
 
    / * Things */
 
    public :
 
    virtual void Delete(void);
    void foo(void);
 
    /* Things */
};
 
class DoubleMotion : public Motion
{
    public :
 
    void Delete(void);
};


The function 'foo' contains "Delete();" somewhere in the code.

Then I create a few objects:

1
2
3
4
5
6
7
8
deque<Motion> someDeQue;

/* Things, then we enter a for loop */

DoubleMotion* NewMotion = new DoubleMotion(...);
someDeQue.push_back(*NewMotion); 

/* This is done several times */


Then I use the function foo like that:

someDeQue[0].foo();

and no matter what I do, it always uses Motion::Delete, instead of DoubleMotion::Delete().

Would you know what the problem is? Thanks!
Last edited on
Your deque is only capable of holding Motion objects, so that is all that will ever be stored in it.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
// http://ideone.com/1oWD0K
#include <iostream>

struct base
{
    virtual void print_type() const {
        std::cout << "base\n";
    }
};

struct derived : public base
{
    void print_type() const {
        std::cout << "derived\n";
    }
};

int main()
{
    base b; // b is an object of type base.  It can never be anything else.
    b.print_type();

    derived d;
    d.print_type();

    b = d; // If we set b equal to an object of type derived, it is still an object of type base.
    b.print_type();

    base* ptr = &b;     // ptr is a pointer to some class in the base hierarchy
    ptr->print_type();  // if we point it a a base class object, we get base class behavior

    ptr = &d;           // if we point it a derived class object, we get derived class behavior
    ptr->print_type();
}


Store pointers in your container (preferably of the smart variety.)

Google "object slicing"
You are a life saver!!!

Thank you very much :)
Topic archived. No new replies allowed.