Calling derived class functions from a base class

Feb 1, 2010 at 11:02am
Here is what I'm trying to do:

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
35
36
#include <iostream>

class Base
{
public:
    Base()
    {
        loop();
    }

    virtual void foo()
    {
        std::cout << "Base member called." << std::endl;
    }

    void loop()
    {
        while (true)
        {
            foo();
        }
    }
};

class Child : public Base
{
    void foo()
    {
        std::cout << "Child member called." << std::endl;
    }
};

int main()
{
    Child c;
}


The output is:
Base member called.
Base member called.
Base member called.
Base member called.
Base member called.
...


How can I get it to output this?:
Child member called.
Child member called.
Child member called.
Child member called.
Child member called.
...


Thanks,
JCED
Feb 1, 2010 at 11:29am
Move the call of 'loop' in the Child constructor
Feb 1, 2010 at 1:07pm
Think of the object being constructed one level (class) at a time from the base down through the children. In the base constructor, the object just became a Base, but is not yet a Child.
Feb 1, 2010 at 1:33pm
Bazzy+1
bazzy is right, that's what you ask for..

moorecm+1
nice explanation.. ^^

the base class's constructor is called first before the derive class's contructor..
try to make a default constructor in your derive class in put the loop() function in it.. you'll see what i mean.
Last edited on Feb 1, 2010 at 1:34pm
Feb 1, 2010 at 8:27pm
Thanks, everything works nicely now. (and thanks for explaining why) :)
Topic archived. No new replies allowed.