I am new to C++. While trying sample polymorphism code, I found that base class virtual function definition in derived class is possible only when defined within the derived class or outside with declaration in derived class.
Following code gives error:
class B
{
public:
virtual void f();
};
void B::f() {
std::cout<<"B::f";
}
class D : public B
{
public:
void f2() {int b;}
};
// error: no "void D::f()" member function declared in class "D"
void D::f() {
std::cout<<"D::F";
}
It works if I declare f() inside D. I was wondering why do I nee开发者_开发问答d to explicitly declare the function again when it is already declared in Base class. The compiler can get the signature from Base class right?
Thanks in advance..
You can't add members to a class outside of the class definition. If you want D
to have an override for B::f
then you have to declare it inside the class definition. Those are the rules.
Declaring a member in a base class doesn't automatically give derived classes an identical member. Inheriting from the base gives the derived class all the members of the base class so you can choose whether to override, hide or add to the base classes members but you have to indicate a choice to override in the class definition by declaring the overriding function.
Even though D derives from B and therefore you can call f() on an instance of D, it does not mean you do not need to put the declaration into the header.
Any function you implement must be explicitly declared in the header.
You do not need, however, to put its implementation in there. Just
class D : public B
{
public:
/*virtual*/ void f();
};
and you can optionally choose whether to include the word "virtual" here
In C++, your class definition tells the compiler which functions the class implements. So if you want to write a function "D::f()", you must have f() in the class definition for D.
The fact that function "B::f()" has been defined in the base class is irrelevant. Each class definition must explicitly declare the functions that it implements.
Change code for class D as below and try :
class D : public B
{
public:
void f() override;
};
// error: no "void D::f()" member function declared in class "D"
void D::f() {
std::cout << "D::F";
}
精彩评论