1

If I have a class say

class Base {
 public:
  virtual void func() = 0;
};

That is the base for two other classes

class DerivedA1 : public Base {
 public:
  virtual bool func(string command);
};

class DerivedB1 : public Base {
 public:
  virtual void func();
}

class DerivedA2 : public DerivedA1 {
 public:
  bool func(string command);     //This one implements it differently
};                                 //its base class.

Is the above allowed? I declared func() with no parameters but then I'm using it with parameters. I have a similar situation in my code that I can't post because this is it's part of a school assignment, and am getting an error similar to

error: no matching function for call to Base::fucn(std::string&)
note: candidate is: virtual bool Base::move();
note: candidate expects 0 arguments, provided  1

I want func() to be used differently in its different derived classes. How can I fix this problem?

4
  • No, it isn't allowed. Overrides of virtual functions of the base class must have the exact same signature. Commented Apr 2, 2016 at 18:35
  • There is a concept called contravariance which allows the derived class to change the method's argument (not arbitrarily though), but that does not apply here. You could use default arguments: en.cppreference.com/w/cpp/language/default_arguments Commented Apr 2, 2016 at 18:36
  • You can make another class for the parameter. virtual void func(MyBaseParemeterClass*) = 0; Commented Apr 2, 2016 at 18:37
  • @mike: if default parameters on virtual functions are not identical for all overrides, calling them behaves differently depending on the used type. I find this too brittle and confusing, so I try to avoid default parameters in such situations. Commented Apr 2, 2016 at 18:59

1 Answer 1

2

DerivedA1::func(string) is hiding Base::func(). It's allowed, but won't override the behaviour of Base::func. clang will warn you about this because it's almost always an error

class DerivedA1 : public Base {
 public:
  virtual bool func(string command);
};

This is fine:

class DerivedB1 : public Base {
 public:
  virtual void func();
}

This is overriding DerivedA1::func(string). A virtual function which only exists on a DervivedA1 interface or something derived from it. It does not exist on Base

class DerivedA2 : public DerivedA1 {
 public:
  bool func(string command);     //This one implements it differently
};                  
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.