2

is there any way i can make the following work, or is there a work around? I must be missing something.

class base
{
public:
    int someInt;
    virtual void someFunction(){}
};

class derived : public base
{
public:
    void someFunction(){}
    void anotherFunction(){}
};

int main (int argc, char * const argv[]) {

    base* aBasePointer = new derived;

    aBasePointer->anotherFunction();

    delete aBasePointer

    return 0;
}
3
  • 1
    You need anotherFunction() to be virtual in base as well. Or call it through a pointer to derived. At the moment base knows nothing about this function. Commented Mar 13, 2012 at 17:08
  • What are the real functions? Why do you want to do this? Commented Mar 13, 2012 at 17:18
  • It needs to be virtual AND defined in Base as well. It doesn't help if you add a new virtual function to Derived. Commented Mar 13, 2012 at 19:52

3 Answers 3

7

Use dynamic_cast<> to downcast the pointer to the derived class (don't forget to test the result).

e.g

if ((derived* p = dynamic_cast<derived*>(aBasePointer)))
{
  // p is of type derived.
  p->anotherFunction();
}
Sign up to request clarification or add additional context in comments.

1 Comment

Awesome, just the thing I was after.
1

What Nim suggested will work, but if you're performing downcasts you almost certainly have a design problem. If you explain what you're trying to achieve maybe we can suggest a better alternative.

Comments

-2

This will work

int main (int argc, char * const argv[]) {

    derived* aDerivedPointer = new derived;

    aDerivedPointer->anotherFunction();

    delete aDerivedPointer

    return 0;
}

Other than that, you need to provide more information about what you're trying to accomplish.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.