Celdtun
Celdtun

Reputation: 33

How can I call a derived class's method from a function expecting the a base class pointer?

It has been a very long time since I did a lot of C++ coding and I have forgotten much. Can comeone help to point me in the correct direction?

Assume I have a the following classes:

class A
{
  // Normal Class Stuff
  bool doSomething( void);
}
bool A::doSomething( void)
{
  return( true);
}
class B : private A
{
  // Normal Class Stuff
  bool doSomething( void);
  void doSomethingElse( void);
}
bool B::doSomething( void)
{
  doSomethingElse();
  return( A::doSomething);
}
void B::doSomethingElse( void)
{
  // Something Else
}
class foo
{
  // Normal Class Stuff
  void foo_stuff( A * ptr);
}
void foo_stuff( A * ptr)
{
  if( ptr->doSomething())
  {
    // Some Stuff
  }
}

Is there a way for me to pass in a pointer to class B and have it process B::doSomething without having to rewrite the foo class? In essence, I don't want to have to modify class foo, but I need to be able to perform B::doSomethingElse before I jump to A::doSomething.

Thank you.

Upvotes: 0

Views: 34

Answers (1)

John Park
John Park

Reputation: 1764

The dtor() and the function of base class must be marked virtual.

I changed class A's access keyword to public so that it can be called from class foo.

class A
{
public:
  virtual bool doSomething(void);
  virtual ~A() noexcept;
}

and it is recommend that class B overriding its parent function to append override keyword.

class B : public A
{
public:
  bool doSomething(void) override;
  virtual ~B() noexcept;
}

Upvotes: 1

Related Questions