Home > Blockchain >  Create a fully-functional derived class with just one extra method in C ?
Create a fully-functional derived class with just one extra method in C ?

Time:11-18

This is what I want to do:

class Derived : public Base
{
public:
    int someNewMethod(int someIntParam)
    {
       // Does something not in the base class
       return 0; // success
    }
};

Then I should be able to use Derived in place of Base (while fully aware that the reference may become invalid, depending on when the Base object is deleted):

Derived &d = *pointerToSomeExistingBaseObject;
d.someNewMethod(12);

While somewehere else in code, far, far away (and beforehand):

Base *pointerToSomeExistingBaseObject = new Base(...);

Thank you!

CodePudding user response:

Create a fully-functional derived class with just one extra method in C ?

You can do that. You did that with Derived (assuming someNewMethod isn't in Base).


Derived &d = *pointerToSomeExistingBaseObject;
d.someNewMethod(12);

While somewehere else in code, far, far away (and beforehand):

Base *pointerToSomeExistingBaseObject = new Base(...);

No, you cannot do that. In order to call the non-static member functions of Derived, you must create an object of type Derived or a type derived from it.

CodePudding user response:

The typical solution is to make the function free-standing:

int someNewMethod(Base& obj, int someIntParam)
{
    // Does something with obj that is not in Base
    return 0; // success
}
  • Related