Question on C++ parent and child functions

E

Eric

Consider the following:

class ParentClass
{
public:
void FunctionOne( void );
protected:
void FunctionTwo( void );
private:
void FunctionThree( void );
};


ParentClass::FunctionOne( void )
{
FunctionTwo();
}

ParentClass::FunctionTwo( void )
{
FunctionThree();
}

ParentClass::FunctionThree( void )
{
printf( "Executing parent class's FunctionThree\n" );
}


class ChildClass : public ParentClass
{
public:
void FunctionTwo( void );
void FunctionThree( void );
};

ChildClass::FunctionTwo( void )
{
FunctionThree();
}

ChildClass::FunctionThree( void )
{
printf( "Executing child class's FunctionThree\n" );
}

int main( int argc, char** argv )
{
ChildClass* ccPtr = new ChildClass;

ccPtr->FunctionOne();
}


There is no ChildClass::FunctionOne(), so it's actually
ParentClass::FunctionOne() that gets executed.

My question is, is the call to FunctionTwo() within FunctionOne() a
call to the parent class's FunctionTwo(), or the child class's
FunctionTwo()?

I suspect it's the former (parent class), so my question then becomes,
how do I force it to execute the child class's FunctionTwo()?

Maybe something like pass FunctionOne() the "this" pointer and then
have FunctionOne call FunctionTwo and FunctionThree using the this
pointer (i.e. "CallersThis->FunctionOne()" and
"CallersThis->FunctionTwo()")?
 
P

Pete C

Eric said:
My question is, is the call to FunctionTwo() within FunctionOne() a
call to the parent class's FunctionTwo(), or the child class's
FunctionTwo()?

I suspect it's the former (parent class), so my question then becomes,
how do I force it to execute the child class's FunctionTwo()?

You are correct - it executes the parent's FunctionTwo because
FunctionTwo is not virtual. Declare FuntionTwo and FunctionThree as
virtual (in the parent class, and optionally in the derived class) and
you'll see the behaviour you want.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,774
Messages
2,569,596
Members
45,130
Latest member
MitchellTe
Top