Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pure virtual functions and unused arguments in child functions in C++

I have the following:

class Parent {
public:
    virtual bool foo(vector<string> arg1, vector<string> arg2) = 0;
};

class Child : public Parent {
public:
    bool foo(vector<string> arg1, vector<string> arg2);
};

// arg1 and arg2 not used - GIVES WARNING
bool Child::foo(vector<string> arg1, vector<string> arg2) {
    return false;
}

There is no Parent implementation of foo(...) because it is a pure virtual function. The parent says that foo takes two vector arguments. The child implements it correctly with two string arguments but they're not used. HOWEVER, some children of Parent WILL use these arguments so they need to always be there.

Is there any way I can use overloading to allow foo in the given Child class not to have the arguments even though the parent says it has to?

Many thanks.

like image 427
ale Avatar asked Jul 19 '11 20:07

ale


People also ask

Can pure virtual function have arguments?

Like any other function, a virtual function can have default arguments (§ 6.5. 1, p. 236). If a call uses a default argument, the value that is used is the one defined by the static type through which the function is called.

What is the pure virtual function in C?

A pure virtual function is a function that must be overridden in a derived class and need not be defined. A virtual function is declared to be “pure” using the curious =0 syntax. For example: class Base {

What is virtual function and pure virtual function in C?

A virtual function is a member function of base class which can be redefined by derived class. A pure virtual function is a member function of base class whose only declaration is provided in base class and should be defined in derived class otherwise derived class also becomes abstract.

What happens if a pure virtual function is not redefined in a derived class?

3) If we do not override the pure virtual function in derived class, then derived class also becomes abstract class.


1 Answers

Don't specify the parameter names:

// arg1 and arg2 not used - GIVES WARNING
bool Child::foo(vector<string>, vector<string>) {
    return false;
}

That should solve the warnings.

If your compiler for whatever reason doesn't support it - do this:

// arg1 and arg2 not used - GIVES WARNING
bool Child::foo(vector<string> arg1, vector<string> arg2) {
    (void)arg1; (void)arg2; // ignore parameters without "unused" warning
    return false;
}
like image 88
littleadv Avatar answered Oct 05 '22 13:10

littleadv