Calling the methods of a subclass - c++

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.

Related

Abstract base class implementation

Here is an interview question :
How can we implement an abstract base class without using pure virtual functions.
What we can do so that we cannot create any object of a class because in that case we can say our class is an abstract base class.
At first I thought of using an virtual destructor but I am not sure about this solution because of virtual keyword. Can you please help?
You ask two questions, which we will answer in turn:
How can we implement an abstract base class without using pure virtual functions?
It is impossible, per the definition of an abstract class: "A class is abstract if it has at least one pure virtual function" (C++11 §10.4/2). Therefore, in order to be abstract, a class must declare a pure virtual function or it must inherit one from another class from which it derives.
What we can do so that we cannot create any object of a class?
This question can be interpreted in a number of different ways, each of which has a different solution.
Taken literally, the question asks for a type of which no instance may be created. A class with no defined constructors cannot be constructed.
To accomplish this, one should declare (but not define) a default constructor and copy constructor for the class. If one is using a compiler with support for C++11's deleted special member functions, they should be declared as deleted.
Taken in the context of the first question, it seems more likely that the intent is to define a class that can only be instantiated as a base class subobject of another class.
This can be accomplished by declaring all constructors as protected, not providing any static factory member function that creates instances of the class, and by not befriending any other classes or functions.
A virtual destrutor won't do the required job.You can do either of the following:
Declare a pure virtual destructor with a definition.
Make constructor of the base class protected.
for more clear explanation refer to Making a class abstract without any pure virtual methods.

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)

virtual function declared non-virtual in a derived class

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.

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.

Are virtual destructors inherited?

If I have a base class with a virtual destructor. Has a derived class to declare a virtual destructor too?
class base {
public:
virtual ~base () {}
};
class derived : base {
public:
virtual ~derived () {} // 1)
~derived () {} // 2)
};
Concrete questions:
Is 1) and 2) the same? Is 2) automatically virtual because of its base or does it "stop" the virtualness?
Can the derived destructor be omitted if it has nothing to do?
What's the best practice for declaring the derived destructor? Declare it virtual, non-virtual or omit it if possible?
Yes, they are the same. The derived class not declaring something virtual does not stop it from being virtual. There is, in fact, no way to stop any method (destructor included) from being virtual in a derived class if it was virtual in a base class. In >=C++11 you can use final to prevent it from being overridden in derived classes, but that doesn't prevent it from being virtual.
Yes, a destructor in a derived class can be omitted if it has nothing to do. And it doesn't matter whether or not its virtual.
I would omit it if possible. And I always use either the virtual keyword or override for virtual functions in derived classes for reasons of clarity. People shouldn't have to go all the way up the inheritance hierarchy to figure out that a function is virtual. Additionally, if your class is copyable or movable without having to declare your own copy or move constructors, declaring a destructor of any kind (even if you define it as default) will force you to declare the copy and move constructors and assignment operators if you want them as the compiler will no longer put them in for you.
As a small point for item 3. It has been pointed out in comments that if a destructor is undeclared the compiler generates a default one (that is still virtual). And that default one is an inline function.
Inline functions potentially expose more of your program to changes in other parts of your program and make binary compatibility for shared libraries tricky. Also, the increased coupling can result in a lot of recompilation in the face of certain kinds of changes. For example, if you decide you really do want an implementation for your virtual destructor then every piece of code that called it will need to be recompiled. Whereas if you had declared it in the class body and then defined it empty in a .cpp file you would be fine changing it without recompiling.
My personal choice would still be to omit it when possible. In my opinion it clutters up the code, and the compiler can sometimes do slightly more efficient things with a default implementation over an empty one. But there are constraints you may be under that make that a poor choice.
The destructor is automatically virtual, as with all methods. You can't stop a method from being virtual in C++ (if it has already been declared virtual, that is, i.e. there's no equivalent of 'final' in Java)
Yes it can be omitted.
I would declare a virtual destructor if I intend for this class to be subclassed, no matter if it's subclassing another class or not, I also prefer to keep declaring methods virtual, even though it's not needed. This will keep subclasses working, should you ever decide to remove the inheritance. But I suppose this is just a matter of style.
A virtual member function will make implicitely any overloading of this function virtual.
So the virtual in 1) is "optional", the base class destructor being virtual makes all child destructors virtual too.
1/ Yes
2/ Yes, it will be generated by the compiler
3/ The choice between declaring it virtual or not should follow your convention for overriden virtual members -- IMHO, there are good arguments both way, just choose one and follow it.
I'd omit it if possible, but there is one thing which may incite you to declare it: if you use the compiler generated one, it is implicitly inline. There are time when you want to avoid inline members (dynamic libraries for instance).
Virtual functions are overridden implicitly. When the method of a child class matches the method signature of the virtual function from a base class, it is overridden.
This is easy to confuse and possibly break during refactoring, so there are override and final keywords since C++11 to mark this behavior explicitly. There is a corresponding warnings that forbid the silent behavior, for example -Wsuggest-override in GCC.
There is a related question for override and final keywords on SO: Is the 'override' keyword just a check for a overridden virtual method?.
And the documentation in the cpp reference https://en.cppreference.com/w/cpp/language/override
Whether to use override keyword with the destructors is still a bit of debate. For example see discussion in this related SO question: default override of virtual destructor
The issue is, that the semantics of the virtual destructor is different to normal functions. Destructors are chained, so all base classes destructors are called after child one. However, in case of a regular method base implementations of the overridden method are not called by default. They can be called manually when needed.