I am learning inheritance in C . So for clearing my doubts i am trying out different examples. One such example which i don't understand is given below:
struct Base
{
virtual void func(int a)
{
std::cout<<"base version called"<<std::endl;
}
};
struct Derived: Base
{
void func(int a) const //note the const here: Is this a new function or this function overrides the old virtual from base
{
std::cout<<"derived version called"<<std::endl;
}
};
Note that i have added const for the func member function inside struct Derived. My question is that: is this member function func inside Derive a new(separate from func inside Base) function or does this func in Derived overrides the old virtual func from Base?
PS: My question is not about the meaning of const here since i know that in this context it means a const member function which means that that the object to which this pointer points is treated as const object. My question is whether func inside Derived a different function that the one inside Base.
CodePudding user response:
The member function func inside Derived is a separate/different non-virtual member function from the virtual func inside Base, as explained below.
Explanation
You can confirm this:
- by adding the keyword
overrideafterconstoffuncinDerivedas shown here you will see the error saying
marked override, but does not override
This confirm that the func in Derived does not override the virtual from func from Base.
struct Derived: Base
{
void func(int a) const override //added keyword override. This gives error now
{
std::cout<<"derived version called"<<std::endl;
}
};
- moreover, by adding the keyword
finalafter theconstoffuncinDerivedas shown here you will see the error saying
marked final, but is not virtual
This confirm that the func in Derived is a non-virtual member function.
struct Derived: Base
{
void func(int a) const final //added keyword final. This gives error now
{
std::cout<<"derived version called"<<std::endl;
}
};
Combining these two points, we come to the conclusion that func inside Derived is a non-virtual member function that is separate from the virtual member function func inside Base.
Also note that there is another way of confirming that the func inside Derived is a nonvirtual member function by just declaring it and not defining it as shown here because we must define a virtual member function. On the other hand if the member function is nonvirtual we can have its declaration without having its definition as long as we do not call that member function.
struct Derived: Base
{
void func(int a) const; //note this is a declaration and not a definition. This works as long as you do not call this function. You cannot do this with a virtual member function
};
CodePudding user response:
void func(int a) const inside Derived is a different member function, once a function declared by const, another new function is born. ### 52.231.8.65 ###
