Q_A
Q_A

Reputation: 451

C++ - Parameters of a pure virtual function

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?

Upvotes: 1

Views: 1731

Answers (1)

Richard Hodges
Richard Hodges

Reputation: 69882

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
};                  

Upvotes: 2

Related Questions