virtual function declared non-virtual in a derived class - c++

If a function is declared non-virtual in a derived class when the base class function was virutal, why does it invoke a vtable lookup on calling the function on its pointer? The function is clear from the scope.

In C++ if you declare a method virtual in the base class then it's virtual also in derived class, even if the virtual keyword is omitted.
For documentation purposes is however in my opinion nice to repeat it anyway.

You cannot make a function non-virtual, so it will stay virtual and a call to the function is in general also virtual. Of course, there are situations where the compiler will be able to optimize this and do a direct call, but apparantly not in your scenario.

The function is still virtual (assuming it has the same or a covariant signature). Using virtual when overriding is redundant.

Virtual methods created to affect on derived class (When you mark a method as virtual. It will use vtable on derived classes). And the overrided methods will be virtual.

When a class inherits a virtual function, any new, overriding declaration of that function will automatically be made virtual, even if the virtual keyword is not used.

Related

Turning a non-pure virtual function into pure in a subclass

So, I have this polymorphic hierarchy:
ClassA
Is not abstract, no pure virtual functions, but a few virtual functions
ClassB:public ClassA
Defines an extended interface for a certain type of subclass;
is abstract with pure virtual functions
ClassC:public ClassB
Usable class, no more subclassing
Here's the deal, I will have objects of ClassA and ClassC thrown together into containers and iterated through. To perform this iteration, a non-pure virtual function is present in ClassA but is empty with just {}; that is, it is empty, made available only if the iteration encounters a ClassC in which case it is invoked, otherwise it does nothing. I can't have it be pure otherwise I cannot have objects of ClassA.
But to ensure that ClassC does in fact implement that function, forcing the user of that class to do so, I make this function pure virtual in ClassB.
Is this acceptable? Nothing will "break" if I take a non-pure virtual function, make it pure, then make it non-pure again in ClassC ?
You're fine if implemented as you present in your explanation. Without going into entire sections on abstract base classes and virtual functions, the standard dictates:
C++ § 10.4p2
An abstract class is a class that can be used only as a base class of some other class; no objects of an abstract class can be created except as subobjects of a class derived from it. A class is abstract if it has at least one pure virtual function. [ Note: Such a function might be inherited: see below. — end note ] A virtual function is specified pure by using a pure-specifier (9.2) in the function declaration in the class definition. A pure virtual function need be defined only if called with, or as if with (12.4), the qualified-id syntax (5.1)
The "below" referenced above leads to this note:
C++11 § 10.4p5
[Note: An abstract class can be derived from a class that is not abstract, and a pure virtual function may override a virtual function which is not pure. - end note]
a non-pure virtual function is present in ClassA but not implemented;
That results in linker error. When creating an objects of ClassA or its subclasses, all virtual methods must be implemented. Only for pure virtual methods the body of the method is optional.
But to ensure that ClassC does in fact implement that function,
forcing the user of that class to do so, I make this function pure
virtual in ClassB.
Yes, this way is correct. But, you should also evaluate that, is it worth having a new class just to make sure that few methods are implemented or not?
For C++11, you can think of making smart use of override identifier as well.
Also, you should not worry about the internal details of vtable, as they are implementation defined.

what does value assignment to a function do? On a virtual function

I need to understand these statements:
virtual string FOOy() = 0;
virtual string FOOx( bool FOOBAR ) = 0;
I am not sure if the function being virtual has anything to do with it...
Although your testcase is woefully incomplete, from the presence of the keyword virtual it looks like this is inside a class definition.
In such a context, = 0 is not an assignment at all, but a piece of confusing syntax that marks the virtual member function as being "pure". A pure virtual member function may have an implementation (defined elsewhere), but one is optional and the function's very existence prohibits the class from being instantiated.
That is, a class with pure virtual member functions may be called "abstract".
Your peer-reviewed C++ book covers the topic in much greater detail.
It means that the method is pure, or abstract. It means that the method is meant to be declared by extending classes (thanks for clarifying this--see comments below).
The = 0 syntax is how you declare a pure virtual function in C++. A pure virtual has no implementation in the class declaring it -- any subclass must implement the function in order to be instantiable.
http://www2.research.att.com/~bs/glossary.html#Gpure-virtual-function
That makes the function a pure virtual function. This means that the class that declares the function is abstract, and subclasses must provide an implementation for this function.
By adding the = 0 you are declaring the virtual function to be pure virtual function. This means that derived classes must implement the method before they can be instantiated. Normally the base class does not have implementation.
This is also called an abstract function in other languages, such as Java and C#.
It simply means, that the implementor (Original writer) of the class in which FOOx and FOOy intended it to be used as an interfaces to its Derived Classes.
And these being virtual means, it will be possible that the derived class' implementation will be used, using the base class' pointer. So its being usable as an interface becomes possible by declaring them as virtual.
And finally, answering your question. Value-assignment, specifically assigning 0 to a function means, explicitly saying, that function doesn't has any definition. (Though you can specify a definition for it, but it will need to be called explicitly by the derived classes)

Calling the methods of a subclass

I have the classes Foo and Bar, where Bar inherits from Foo. Both classes have a getLength() method. I have a function in my main that takes the superclass Foo object as a parameter, but it is often passed a Bar object.
When the Bar object is passed, why does it still call the Foo getLength() method?
Sorry if this is a silly question, but did you mark both getLength() functions as "virtual"? (You need to.)
You should define your method as virtual if a child class may override it.
You need to declare the method virtual in the base class.
Remember that classes with any virtual methods should also have a virtual destructor.
Plenty of info here: http://www.parashift.com/c++-faq-lite/virtual-functions.html
You need to declare the method as virtual.
class Foo
{
virtual double getLength();
}
Everyone is right, of course, in that you need to mark the function as being virtual. But why is this the case?
In C++, non-virtual function calls are resolved at compile time using the type of the reference, not the actual type of the object. So this is why in your case the Foo::getLength() function is being called — your function is declared to use a Foo.
If you declare a function to be virtual, however, the actual type of the object determines which function gets called.
Read the virtual functions section of the C++ FAQ for all the gory details.
(Contrast this scenario to a language like Java where instance methods are virtual by default.)
You have to declare Foo's getLength() function as virtual. Please go through the below link for explanation about virtual functions, hiding virtualization, virtual tables etc
[http://www.learncpp.com/cpp-tutorial/122-virtual-functions/]
And of course there's the interview question gotcha of one being declared const and the other not!
"virtual" keyword is required in declaration of getLength(). And rememder to create virtual destructor in every class to correctly free the resources. Because if you use a pointer to base class that points to derived and call a non-virtual destructor, only base class destructor will be called. If you add virtual destructor, then derived class destructor will be called first, and base class destructor after it. It is usefull when you obtain extra resources in derived class and need to free it first. And base class destructor can't make it because it didn't know about extra resources.

Set a virtual function declaration to zero? [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Why pure virtual function is initialized by 0?
In C++, what does it mean to set a function declaration to zero? I'm guessing it has to do with the function being virtual, and not actually defined in this class. Found in a header file of code that I'm reading:
virtual void SetValue(double val)=0;
What's going on here?
It's a pure virtual function. It makes it so you MUST derive a class (and implement said function) in order to use it.
This is called a pure virtual member function in C++ lingo. It means, as you guessed, that the function is not defined within the class, but rather has to be implemented in deriving classes. You cannot instantiate classes with pure virtual member functions, pure virtual functions basically behave like abstract methods in Java or C#.
It means that it is a pure virtual method - which means subclasses must implement the method on their own. There can still be an implementation for that method, but classes with pure virtual methods cannot be instantiated, making this similar to the abstract keyword seen in various other languages.
if you set a virtual function to set, Its called Pure Virtual Functions. And then your class becomes an abstract class.
You can't create instances of that class or any subclasses unless your pure virtual functions are implemented.
The method SetValue is pure virtual. Its class does not provide the implementation of that method, and can not be instantiated (therefore we term it abstract). Concrete derived classes on the other hand have to provide implementations for such methods. See more here.
It means that, the class is abstract, and can't be create its object. It could be used as a base class to another. Pure virtual class is also used in c++ as an interface known from language like java, but of course it is different.
As everyone has mentioned, this means that the function is a pure virtual function. Think of of this as setting the function pointer to null. Classes with pure virtual functions are handled as abstract classes. This means that derived classes must implement this virtual function.
Occasionally, you may encounter what is called a "pure call" error. This means that a pure virtual function was actually called and it will most likely cause the program to crash. The most common cause of a pure call is that the object that the function was called on was already deleted.
"SetValue" is a pure virtual member function that the base class forces derived classes to provide. Pure virtual member functions will have no implementation.
A pure virtual member function specifies that a member function will exist on every object of a concrete derived class even though the member function is not (normally) defined in the base class.
This is because the syntax for specifying a pure virtual member function forces derived classes to implement the member function if the derived classes intend to be instantiated (that is, if they intend to be concrete).
In your case, all objects of classes derived from the base class will have the member function SetValue(). However, because the base class is an abstract concept, it does not contain enough information to implement SetValue().
Imagine that the "= 0" is like saying "the code for this function is at the NULL pointer."
Pure virtual member functions allow users to write code against an interface for which there are several functionally different variants. This means that semantically different objects can be passed to a function if these objects are all under the umbrella of the same abstract base class.

Behavior of virtual function in C++

I have a question, here are two classes below:
class Base{
public:
virtual void toString(); // generic implementation
}
class Derive : public Base{
public:
( virtual ) void toString(); // specific implementation
}
The question is:
If I wanna subclass of class Derive perform polymophism using a pointer of type Base, is keyword virtual in the bracket necessary?
If the answer is no, what's the difference between member function toString of class Derive with and without virtual?
C++03 §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.
That keyword there is strictly optional and makes no difference at all.
The virtual property is inherited from the base class and is assumed to be present even if you don't type it out.
The compiler already knows from the 'virtual' keyword in the base class that toString is a virtual method. No need to repeat it.
A function once a virtual always a virtual.
So in any event if the virtual keyword is not used in the subsequent classes, it does not prevent the function/method from being 'virtual' i.e. be overridden. So the following guideline might help from a team development point-of-view :-
If the function/method is supposed to
be overridden, always use the
'virtual' keyword. This is especially
true when used in interface / base
classes.
If the derived class is supposed to
be sub-classed further explicity
state the 'virtual' keyword for every
function/method that can be
overridden.
If the function/method in the derived
class is not supposed to be
sub-classed again, then the keyword
'virtual' is to be commented
indicating that the function/method
was overridden but there are no
further classes that override it
again. This ofcourse does not prevent
someone from overriding in the
derived class unless the class
is made final (non-derivable), but it
indicates that the method is not supposed to be
overridden.
Ex: /*virtual*/ void someFunc();
It doesn't matter to the compiler whether or not you supply the virtual keyword on derived versions of the function.
However, it's a good idea to supply it anyway, so that anyone looking at your code will be able to tell it's a virtual function.
It's a matter of good style, and the user-programmer knows what's going on. In C++0x you can use [[override]] to make it more explicit and visible. You can use [[base_check]] to force the usage of [[override]].
If you don't want or can't do that, simply use the virtual keyword.
If you derive without virtual toString, and you cast an instance of Derive back to Base, calling toString() would actually call Base's toString(), since as far as it know's that's an instance of Base.