user72603
user72603

Reputation: 997

How to override a Base Class method and add a parameter

I have this in my base class:

protected abstract XmlDocument CreateRequestXML();

I try to override this in my derived class:

protected override XmlDocument CreateRequestXML(int somevalue)
{
    ...rest of code
}

I know this is an easy question but because I've introduced a param is that the issue? The thing is, some of the derived classes may or may not have params in its implementation.

Upvotes: 6

Views: 13348

Answers (4)

Patrick Peters
Patrick Peters

Reputation: 9568

I am very curious what you are trying to accomplish with this code.

Normally you define an abstract function when a usage class knows its signature. The usage class has a "contract" with you base class.

When you want to derive from the baseclass and add additional parameters, how does the usage class know what to call on the base class anyway?

It looks like an architectual flaw....but maybe you can add some extra information to the inital topic.

Upvotes: 1

Steve Rowe
Steve Rowe

Reputation: 19423

If some of the derived classes need paramters and some do not, you need to have two overloaded versions of the method. Then each derived class can override the one it needs.

class Foo {    
    protected abstract XmlDocument CreateRequestXML(int somevalue);
    protected abstract XmlDocument CreateRequestXML();
};

class Bar : public Foo {    
    protected override XmlDocument CreateRequestXML(int somevalue) { ... };
    protected override XmlDocument CreateRequestXML()
        { CreateRequestXML(defaultInt); }
};

This of course introduces a problem of the user calling the wrong one. If there is no acceptable default for the extra paramter, you may have to throw an exception in the derived class if the wrong version is called.

Upvotes: 2

JaredPar
JaredPar

Reputation: 754515

When you override a method, with the exception of the word override in place of virtual or abstract, it must have the exact same signature as the original method.

What you've done here is create a new unrelated method. It is not possible to introduce a parameter and still override.

Upvotes: 14

John Rasch
John Rasch

Reputation: 63435

Yes the parameter is the issue, the method signature must match exactly (that includes return value and parameters).

Upvotes: 0

Related Questions