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 need 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..
According to the C++ standard, a virtual member function declared in the definition of a class must have a definition (implementation). Remember that, when you are trying to give implementation of a virtual member function, you cannot mark virtual again outside the class definition.
This was a rather long-winded way of calling out a weird corner case in C++ that most people don't even realize exists: A pure virtual function can have an implementation.
Functions should be declared inside the class to bound it to the class and indicate it as it's member but they can be defined outside of the class. To define a function outside of a class, scope resolution operator :: is used.
In C++, a call to the virtual area function applied to a shape looks exactly like a non-virtual call, as in: shape *s;~~~s->area(); If s points to a circle (the dynamic type of *s is circle ), then the call above calls circle::area . If s points to a rectangle , then the call above calls rectangle::area .
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";
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With