Does the virtual qualifier to a virtual function of base class, in the derived class makes any difference ?
class b
{
public:
virtual void foo(){}
};
class d : public b
{
public:
void foo(){ .... }
};
or
class d : public b
{
public:
virtual void foo(){ .... }
};
Is there any difference in these two declarations, apart from that it makes child of d make aware of virtuality of foo() ?
It makes no difference. foo is virtual in all classes that derive from b (and their descendants).
From C++03 standard, §10.3.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 and same parameter list as Base::vf is declared, then Derived::vf is also virtual (whether or not it is so declared) and it overrides Base::vf.
No difference - it's a virtual override either way.
It's a matter of style and has been definitively discussed here
It's better style to include the virtual keyword. But it's not required.
No difference.
Once foo is virtual, its virtual forever in the class-hierarchy, no matter how far you go from the base in the class-hierarchy.
But I prefer to write virtual even in overrridden functions, because it adds readability to the code, which matters a lot.
Related
My basic understanding is that there is no implementation for a pure virtual function, however, I was told there might be implementation for pure virtual function.
class A {
public:
virtual void f() = 0;
};
void A::f() {
cout<<"Test"<<endl;
}
Is code above OK?
What's the purpose to make it a pure virtual function with an implementation?
A pure virtual function must be implemented in a derived type that will be directly instantiated, however the base type can still define an implementation. A derived class can explicitly call the base class implementation (if access permissions allow it) by using a fully-scoped name (by calling A::f() in your example - if A::f() were public or protected). Something like:
class B : public A {
virtual void f() {
// class B doesn't have anything special to do for f()
// so we'll call A's
// note that A's declaration of f() would have to be public
// or protected to avoid a compile time problem
A::f();
}
};
The use case I can think of off the top of my head is when there's a more-or-less reasonable default behavior, but the class designer wants that sort-of-default behavior be invoked only explicitly. It can also be the case what you want derived classes to always perform their own work but also be able to call a common set of functionality.
Note that even though it's permitted by the language, it's not something that I see commonly used (and the fact that it can be done seems to surprise most C++ programmers, even experienced ones).
To be clear, you are misunderstanding what = 0; after a virtual function means.
= 0 means derived classes must provide an implementation, not that the base class can not provide an implementation.
In practice, when you mark a virtual function as pure (=0), there is very little point in providing a definition, because it will never be called unless someone explicitly does so via Base::Function(...) or if the Base class constructor calls the virtual function in question.
The advantage of it is that it forces derived types to still override the method but also provides a default or additive implementation.
If you have code that should be executed by the deriving class, but you don't want it to be executed directly -- and you want to force it to be overriden.
Your code is correct, although all in all this isn't an often used feature, and usually only seen when trying to define a pure virtual destructor -- in that case you must provide an implementation. The funny thing is that once you derive from that class you don't need to override the destructor.
Hence the one sensible usage of pure virtual functions is specifying a pure virtual destructor as a "non-final" keyword.
The following code is surprisingly correct:
class Base {
public:
virtual ~Base() = 0;
};
Base::~Base() {}
class Derived : public Base {};
int main() {
// Base b; -- compile error
Derived d;
}
You'd have to give a body to a pure virtual destructor, for example :)
Read: http://cplusplus.co.il/2009/08/22/pure-virtual-destructor/
(Link broken, use archive)
Pure virtual functions with or without a body simply mean that the derived types must provide their own implementation.
Pure virtual function bodies in the base class are useful if your derived classes wants to call your base class implementation.
Yes this is correct. In your example, classes that derive from A inherit both the interface f() and a default implementation. But you force derived classes to implement the method f() (even if it is only to call the default implementation provided by A).
Scott Meyers discusses this in Effective C++ (2nd Edition) Item #36 Differentiate between inheritance of interface and inheritance of implementation. The item number may have changed in the latest edition.
The 'virtual void foo() =0;' syntax does not mean you can't implement foo() in current class, you can. It also does not mean you must implement it in derived classes.
Before you slap me, let's observe the Diamond Problem:
(Implicit code, mind you).
class A
{
public:
virtual void foo()=0;
virtual void bar();
}
class B : public virtual A
{
public:
void foo() { bar(); }
}
class C : public virtual A
{
public:
void bar();
}
class D : public B, public C
{}
int main(int argc, const char* argv[])
{
A* obj = new D();
**obj->foo();**
return 0;
}
Now, the obj->foo() invocation will result in B::foo() and then C::bar().
You see... pure virtual methods do not have to be implemented in derived classes (foo() has no implementation in class C - compiler will compile)
In C++ there are a lot of loopholes.
Hope I could help :-)
If I ask you what's the sound of an animal, the correct response is to ask which animal, that's exactly the purpose of pure virtual functions, or abstract function is when you cannot provide an implementation to your function in the base class (Animal) but each animal has its own sound.
class Animal
{
public:
virtual void sound() = 0;
}
class Dog : public Animal
{
public:
void sound()
{
std::cout << "Meo Meo";
}
}
One important use-case of having a pure virtual method with an implementation body, is when you want to have an abstract class, but you do not have any proper methods in the class to make it pure virtual. In this case, you can make the destructor of the class pure virtual and put your desired implementation (even an empty body) for that. As an example:
class Foo
{
virtual ~Foo() = 0;
void bar1() {}
void bar2(int x) {}
// other methods
};
Foo::~Foo()
{
}
This technique, makes the Foo class abstract and as a result impossible to instantiate the class directly. At the same time you have not added an additional pure virtual method to make the Foo class abstract.
In Cplusplus, in a derived class, if we define a member function to override a member function in its parent class, do we need to declare the one in the derived class to be virtual?
For example, do we need to declare g to be virtual in B in order for it to override A::g? which one of the following is correct for the above purpose?
class A{
public:
void f(){printf("A");}
virtual void g(){printf("A");}
}
class B : public A{
public:
void f(){printf("B");}
void g(){printf("B");}
}
or
class A{
public:
void f(){printf("A");}
virtual void g(){printf("A");}
}
class B : public A{
public:
void f(){printf("B");}
virtual void g(){printf("B");}
}
Thanks.
Once a method is virtual in a class, its child class has also these virtual class even if you don't add virtual to them.
Adding override is a good habit to avoid subtle error:
class A{
public:
void f() { printf("A"); }
virtual void g() { printf("A"); }
};
class B : public A{
public:
void f() { printf("B"); }
void g() override { printf("B"); }
};
No you don't. The function is virtual from the first point in the hierarchy where you declare it as such.
You can and should specify it as override in c++11 and onward. It specifies explicitly to the compiler that you are trying to override a virtual function in a base class. It than emits an error if you misspell the function name, mistype the parameters or do anything else that can be considered as adding an overload of the function. Prior to c++11, the previous mistakes would silently compile.
Defining member functions virtual in derived classes is optional. You can make the override explicit using C++11's override.
They both do the same thing. You don't need to explicitly say virtual in the derived class, as long as it is virtual in the base class.
In Cplusplus, in a derived class, if we define a member function to override a member function in its parent class, do we need to declare the one in the derived class to be virtual?
From the working draft, [class.virtual]/2 (emphasis mine):
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) and it overrides Base::vf.
So, no. It is not required.
In pre-C++11 era, declaring virtual also the member functions in the derived classes helped the readers understanding what's going on under the hood.
Since C++11, override is the preferred way, for it not only helps the readers, but also it forces a compile-time check so that typos in the declarations don't introduce subtle errors.
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.
Consider the following base class:
class Base
{
public:
virtual ~Base(void);
virtual void foo(void);
virtual void bar(void) = 0;
}
Now suppose I know that a given class should be the most derived class of Base. Should I declare the functions virtual? The most derived class can/will be used polymorphically with Base.
For example, should I use MostDerived1 or MostDerived2?
class MostDerived1 : public Base
{
public:
~MostDerived1(void);
void foo(void);
void bar(void);
}
class MostDerived2 : public Base
{
public:
virtual ~MostDerived2(void);
virtual void foo(void);
virtual void bar(void);
}
I'm leaning towards MostDerived1 because it most closely models the intent of the programmer: I don't want another child class of MostDerived1 to be used polymorphically with MostDerived1.
Is this reasoning correct? Are there any good reasons why I should pick MostDerived2, aside from the obvious there could be a >0% chance MostDerived2 should be used polymorphically with any deriving classes (class OriginalAssumptionWrong : public MostDerived2)?
Keep in mind MostDerived1/MostDerived2 can both be used polymorphically with Base.
Adding virtual to derived classes doesn't change their behavior, MostDerived and MostDerived2 are have exactly the same behavior.
It does however document your intention, however. I would recommend it for that purpose. The override keyword also helps with this, assuming its available on your platform.
You can't turn off virtualness. Another class derived from either MostDerived1 or MostDerived2 can also override any of the virtual functions regardless of whether you omit the virtual keyword somewhere in the class hierarchy or not.
If you want to enforce that no other class derives from MostDerived1, define it as
class MostDerived1 final : public Base
{
// ...
};
The final keyword can also be used for individual virtual member functions, ensuring no derived class overrides that specific function.
Once function declear somewhere at the hierarchy as a virtual, it's virtual for ever.
You can use final or override if you using C++11
Why do I sometimes see in C++ examples when talking about subclassing / inheritance, the base class has virtual keyword and sometimes the overridden function has also the virtual keyword, why it's necessary to add to the subclass the virtual key word sometimes?
For example:
class Base
{
Base(){};
virtual void f()
......
}
};
class Sub : public Base
{
Sub(){};
virtual void f()
...new impl of f() ...
}
};
It is not necessary, but it helps readability if you only see the derived class definition.
§10.3 [class.virtual]/3
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 and same parameter list as Base::vf is declared, then Derived::vf is also virtual (whether or not it is so declared) and it overrides 97) Base::vf.
Where footnote 97) basically states that if the argument list differs, the function will not override nor be necessarily virtual