How to call inherited class function

Hi

Suppose I have a class Parent and a class Child. Child is an inherited class of Parent. Child also has a class function Function() (which is not a base class function).

I then have another class Process, which takes objects of class Parent by reference in its constructor (for the purposes of generality). The actual object that is fed in in main() however is of class Child - let call this childArg.

I realise that pre-compilation, Process doesn't know that childArg is of class Child yet.

So how do you call the Child class Function() within the source code of Process?

Many thanks
You would have to make Function a member of Parent (and have it be virtual).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Parent
{
public:
   virtual void Function()
   {
      //perhaps empty
   }
};

class Child : public Parent
{
public:
   virtual void Function()
   {
      //do Child specific stuff
   }
};

void Process(Parent& p)
{
   p.Function(); //will call Child::Function if caller passed a Child
}
ahhhh, thank you!
Topic archived. No new replies allowed.