This question already has answers here:
C++ "virtual" keyword for functions in derived classes. Is it necessary?
(9 answers)
Closed 6 years ago.
The following code is late binding test() method but shouldn't it bind early? because test() method is not virtual in class B(but in class A), and we are using pointer of class B.
class A{
public:
virtual void test(){
cout<<"test a";
}
};
class B : public A{
public:
void test(){
cout<<"Test b";
}
};
class C: public B{
public:
void test(){
cout<<"test c";
}
};
int main(){
B *bp;
C objc;
bp = &objc;
bp->test(); // test c
}
Once a function has been declared virtual in a class, it's always virtual in the classes that inherit from that class, whether you use the virtual keyword or not.
So in your class C, the test() function is actually overriding B and A's own test() functions.
N4296, 10.3§2 (draft version):
If a virtual member function vf is declared in a class Base and in a
class Derived, derived directly or indirectly from Base, a member
function vf with the same name, parameter-type-list (8.3.5),
cv-qualification, and ref-qualifier (or absence of same) as Base::vf
is declared, then Derived::vf is also virtual (whether or not it is so
declared) and it overrides Base::vf.
Emphasis by me.
A virtual function remains virtual in all derived classes, regardless if it is declared as virtual in the derived classes.
Related
This question already has an answer here:
method in the derived class got executed without a *virtual* keyword in the referred class
(1 answer)
Closed 2 years ago.
Probably, i misunderstood c++ polymorphism(virtual function).
Please point me what i miss.
the source code is below
#include <iostream>
using namespace std;
class A {
public:
virtual void print(void) {
cout<<"class A"<<endl;
}
};
class B : public A {
public:
void print(void) {
cout<<"class B"<<endl;
}
};
class C : public B {
public:
void print(void) {
cout<<"class C"<<endl;
}
};
int main() {
A a;
B b;
C c;
A *pAa = &a;
A *pAb = &b;
A *pAc = &c;
B *pBc = &c;
pAa->print();
pAb->print();
pAc->print();
pBc->print(); // shouldn't be "class B"
return 0;
}
result
------------------------------
class A
class B
class C
class C // shouldn't be "class B"
my understanding is that
the last print statement should print "class B"
because pBc is a pointer of class B and the print function in class B is non virtual member function. i could not find the answer about this situation.
please tell me why or point me where i can find the answer and
understand c++ polymorphism in comprehension.
thanks.
If a function with a given signature is declared as virtual in a top-level base class, then the function is virtual in all derived classes no matter if it is marked with the keyword virtual (override, final) or not:
virtual function specifier
Then this function in the class Derived is also virtual (whether or not the keyword virtual is used in its declaration)
struct Base {
// Pure virtual function.
virtual void foo() const = 0;
};
struct A : public Base {
// Overriding virtual function, even if it
// is not marked as virtual (override, or final).
void foo() const {}
};
In A, adding the virtual specifier to foo() would only bring semantic value; it will be no functional difference whether virtual is omitted or not (unless someone changes the interface in Base).
Many static analyzers enforce(1) marking derived virtual functions with override or final, for two reasons:
semantics; clearly showing the given function is a virtual function (as per being defined so higher up in the inheritance chain), and
enforcement; if a function is marked as override and final but is not actually an overriding function, you will get a compiler error, which can be particularly useful to protect against mistakes when changing a base class interface (whilst forgetting which classes that actually implements this interface).
E.g.:
struct Base {
// Pure virtual function.
virtual void foo() const = 0;
};
struct A : public Base {
// Overriding virtual function.
void foo() const override {}
};
struct B final : public Base {
// Overriding (final) virtual function.
void foo() const final {}
// Error: Function does not override.
// void bar() const override {}
};
(1) E.g. Rule A10-3-1 in the Autsar C++14 Language Guidelines (safety-critical development in automotive) is categorized as a required rule: Virtual function declaration shall contain exactly one of the three specifiers:(1) virtual, (2) override, (3) final.
the print function in class B is non virtual member function
No. Since A::print is marked as virtual and B inherits from A, then B::print is virtual too; regardless of the keywork virtual is specified on it or not.
(emphasis mine)
If some member function vf is declared as virtual in a class Base, and
some class Derived, which is derived, directly or indirectly, from
Base, has a declaration for member function with the same
name
parameter type list (but not the return type)
cv-qualifiers
ref-qualifiers
Then this function in the class Derived is also virtual (whether or not the keyword virtual is used in its declaration) and overrides Base::vf (whether or not the word override is used in its declaration).
class A
{
public:
virtual void display_A(A* obja)
{
cout<<"Class A"<<endl;
}
};
class B:public A
{
public:
void display_A(B* objb)
{
cout<<"Class B"<<endl;
}
};
int main()
{
A AOBJ;
B BOBJ;
A *obja = new B();
obja->display_A(&AOBJ);
obja->display_A(&BOBJ);
return 0;
}
There is a virtual function in class A having parameter as A* and we are overriding the same function in the derived class B with parameter B*.
I have created a pointer obja (pointer to class A) which is pointing to derived class object B. When I am calling the function display_A with obja pointer with argument as class A object pointer and class B object pointer, I am getting o/p as
Class A
Class A
I am unable to understand why I am getting that o/p.
It's not overriding because the parameter's type is not the same.
If some member function vf is declared as virtual in a class Base, and
some class Derived, which is derived, directly or indirectly, from
Base, has a declaration for member function with the same
name
parameter type list (but not the return type)
cv-qualifiers
ref-qualifiers
Then this function in the class Derived is also virtual (whether or
not the keyword virtual is used in its declaration) and overrides
Base::vf (whether or not the word override is used in its
declaration).
Using override specifier could help you find the error at compile time.
Specifies that a virtual function overrides another virtual function.
In a member function declaration or definition, override ensures that the function is virtual and is overriding a virtual function from the base class. The program is ill-formed (a compile-time error is generated) if this is not true.
class B:public A
{
public:
void display_A(B* objb) override
// ^^^^^^^^
{
cout<<"Class B"<<endl;
}
};
When calling display_A via an A*, either a virtual func of A or B or a non-virtual func of A is called. Since the prototypes are different, the only function matching this criteria is A::display_A.
This question already has answers here:
virtual qualifier in derived class
(4 answers)
Closed 7 years ago.
I'm reading about virtual functions and now little confused about overriding virtual functions.
I want to confirm that below given codes are same?
class A{
public:
virtual void fun(){ }
};
class B :public A{
public:
void fun(){}
};
and
class A{
public:
virtual void fun(){ }
};
class B :public A{
public:
virtual void fun(){}
};
If not same then what's the difference? As I expected that B's function with virtual keyword could be same as for B's Derived. Please clear my confusion thanks.
Yes, they are the same. Any function overriding a virtual function in the base class is implicitly declared virtual.
From the last working draft of the c++14 standard:
10.3 Virtual functions [class.virtual]
If a virtual member function vf is declared in a class Base and in a class Derived, derived directly or indirectly from Base, a member function vf with the same name, parameter-type-list (8.3.5), cv-qualification, and ref- § 10.3 249 c ISO/IEC N4296 qualifier (or absence of same) as Base::vf is declared, then Derived::vf is also virtual (whether or not it is so declared) and it overrides(111) Base::vf.
Emphasis mine
As #Mats and #ixSci pointed out, it is good practice since c++11, to use the keyword override to ensure that you are actually overriding a virtual function and not acidentally overloading a function or overriding a non-virtual function.
Personally, my preferred style is this, but it is up to debate whether the virtual keyword in B adds any value or is even harming readability:
class A{
public:
virtual void fun(){ }
};
class B :public A{
public:
virtual void fun() override {}
};
virtual keyword on the overridden function is completely useless. It doesn't provide anything except readability(some might say it harms readability) but it was the only way in C++03 to convey to the class readers that the function is actually virtual without them checking the base class.
Nowadays it is better to use the keyword which is intruduced specifically for the overriding - override. So your example will look like:
class A{
public:
virtual void fun(){ }
};
class B :public A{
public:
void fun() override{}
};
Not only does it convey the intent but it also makes sure you won't make any mistake when overriding a virtual function.
Virtual keyword tells compiler that there function may be implemented later by inheriting class ( pure virtual). Additionally in c++11 there is keyword override wich checks if implemented method in inheriting class overrodes virtual method of base class. In case of implemented function there is no much difference. We can sam that in case of virtual we talk avout override in other case about hiding of base method ( in both cases your cab still invoke implementation of base). Additionally this is information for programmer that function is intended to override. Additionaly virtual keyword is important in case of destructor. As general rule of thumb if function has some virtual methods it is good to have it a virtual destructor.
I know the title's statement is true.
What about a regular function?
For example
class Father {
virtual void foo() {...;}
}
class Son : public Father {
void foo() {...;}
}
class GrandSon : public Son {
void foo() {...;}
}
Can GrandSon override Son's foo? In general, if your base class has a virtual function, the derived class's corresponding function is automatically virtual?
Is this true?
Yes, in C++ a derived class "inherits" the virtual aspect of all methods--not just destructors.
C++ 2011: 10.3 Virtual Functions
2: If a virtual member function vf is declared in a class Base and in a class Derived, derived directly or indirectly from Base, a member function vf with the same name, parameter-type-list, cv-qualification, and ref-qualifier (or absence of same) as Base::vf is declared, then Derived::vf is also virtual (whether or not it is so declared) ...
This question already has answers here:
Closed 12 years ago.
Possible Duplicates:
C++ : implications of making a method virtual
Why is 'virtual' optional for overridden methods in derived classes?
I wonder, what is documented behavior in the following case:
You have
class A
{
virtual void A()
{
cout << "Virtual A"<<endl;
}
void test_A()
{
A();
}
}
class B: public A
{
void A()
{
cout << "Non-virtual A in derived class"<<endl;
}
void test_B()
{
A();
}
}
A a; B b;
a.test_A();
b.test_A();
b.test_B();
What it supposed to do according to C++ standard and why?
GCC works like B::A is also also virtual.
What shoudl happen in general when you override virtual method by non-virtual one in derived class?
The sub-class member function is implicitly virtual if a virtual base-class member function with the same name and signature exists.
The code should not compile as you cannot name a method with the name of the class. But regarding what I understand that is your real question:
Will making a method virtual imply that the same method in all the derived classes is virtual even if the virtual keyword is not present?
The answer is yes. Once a method is declared virtual in a class, then all overrides of that method will be virtual, and the virtual keyword is optional in derived classes (even if I recommend typing it, if only for documentation purposes). Note that for a method in a derived class to be an override it has to have the same name and signature, with only potential difference being a covariant return type:
struct A {};
struct B : A {};
struct base {
virtual A* foo();
virtual A* bar();
};
struct derived : base {
virtual B* foo(); // override, covariant return type
virtual int bar(); // not override, return type is not covariant
virtual A* bar(int); // not override, different argument list
};
This code is ill-formed. A constructor cannot have a return type (as you have done for the constructor of 'A'). Also a constructor cannot be virtual.
After fixing A's constructor, class B is ill-formed as the constructor of A is private.
So, there are many problems with this code (including missing semicolons at the class definitions).
According to standard it should be
A a; B b;
a.test_A(); //"Virtual A"
b.test_A(); //Non-virtual A in derived class
b.test_B(); //Non-virtual A in derived class