assigning derived class pointer to base class pointer in C++

myfunc needs to be accessible from the base class, so you would have to declare a public virtual myfunc in base. You could make it pure virtual if you intend for base to be an abstract base class, i.e one that cannot be instantiated and acts as an interface:

class base
{
 public:
  virtual void myfunc() = 0; // pure virtual method
};

If you ant to be able to instantiate base objects then you would have to provide an implementation for myfunc:

class base
{
 public:
  virtual void myfunc() {}; // virtual method with empty implementation 
};

There is no other clean way to do this if you want to access the function from a pointer to a base class. The safetest option is to use a dynamic_cast

base* pbase = new derived;

....
derived* pderived = dynamic_cast<derived*>(pbase);
if (derived) {
  // do something
} else {
  // error
}

If you are adamant that this function should NOT be a part of base, you have but 2 options to do it.

Either use a pointer to derived class

derived* pDerived = new derived();
pDerived->myFunc();

Or (uglier & vehemently discouraged) static_cast the pointer up to derived class type and then call the function
NOTE: To be used with caution. Only use when you are SURE of the type of the pointer you are casting, i.e. you are sure that pbase is a derived or a type derived from derived. In this particular case its ok, but im guessing this is only an example of the actual code.

base* pbase = new derived();
static_cast<derived*>(pbase)->myFunc();

To use the base class pointer, you must change the base class definition to be:

class base
{
public:
    virtual void myFunc() { }
};

I see no other way around it. Sorry.

Tags:

C++