Base Class Pointer Accessing Derived Class function.

I have a program like this

class base
{
};

class derived:public base
{
public:
void func();
};

void derived::func()
{
cout << "Hi" << endl;
}

int main()
{
base *p = new derived();
p->func();
return 0;
}

My question is why do I get an error, at line p->func(), saying that "func does not exist in base class".

I know that func() function does not exist in base class, but its pointing to a derived class object having func().
p is a pointer to base so it can access only base members
Try this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>

using namespace std;

class Base
{
  public:
    // believe the compiler: need pure or non-pure virtual here
    virtual void runme() { cerr << "Base" << endl; }   
};

class Derived : public Base
{
  public:
    // virtual here is optional:  I like to put it in for clarity
    virtual void runme() { cerr << "Derived" << endl; }  
};

int main()
{
  Base *p = new Derived;     // get rid of parens
  p->runme();
  return 0;
}


Output:
Derived

Reading up on virtual methods might help.
Last edited on
Thanks
Topic archived. No new replies allowed.