Question about Pure Virtual Functions in C++? - c++

I am reading some C++ text regrading Pure Virtual Functions. As the text says, the form of Pure Virtual Functions declaration, for example, is:
virtual void virtualfunctioname() = 0;
And the text explains: "Since pure virtual function has no body, the programmer must add the notation =0 for declaration of the pure virtual function in the base class."
I have tried to remove = 0;, that means I only declared virtual void virtualfunctioname(); and things worked fine.
So, why do we need to assign a 0 to the virtual function?
Thanks

If a class has any pure virtual functions, it cannot be instantiated. Also, it forces any derived classes to implement those functions, otherwise they too cannot be instantiated.
So if you remove the = 0, you'll just have a normal base class, which may be instantiated, and doesn't enforce an interface on its derived classes. You'll only get into trouble if you instantiate a base-class object (or a derived-class object with no override), and then try to invoke virtualfunctionname() on it, because there's no definition for it, so the linker will complain.
[Note, also the claim that "pure virtual functions have no body" is incorrect; you may define an implementation for a pure virtual. The class will still be abstract, though.]

If you don't declare a method as pure virtual, the compiler will assume there is an implementation of it somewhere. If you never instantiate the class that is supposed to contain those pure virtual (and abstract class to use the right terminology), you will be fine. However, if you do, the compiler will accept the code as valid and you will get a linker error later.
If you mark a method as pure virtual, the class containing it will be marked as abstract and the compiler will refuse any attempts to instantiate it.

things worked fine
I assume you meant that the code compiled and linked. However, you probably haven't defined an implementation for virtualfunctionname in the base class you declare it, so if you ever do call the base implementation you will get a linker error.
At the moment things probably work because you provide an implementation in a derived class and use that instead.

When you declare a function as pure virtual function that class which contain it will known as abstract class and no instance would be created.
Again no instance of that class would be created.This class is used for inheritance and the derived class must implement this method. otherwise compilation error will appear.
Thanks

Related

Adding a body to a pure virtual/abstract function in C++?

A pure virtual function isn't supposed to have a body, but I just noticed that the following code is accepted by the compiler:
class foo
{
virtual void dummy() = 0
{
cout << "hello";
}
};
So, why are pure virtual functions allowed to have a body? Also, even when the function has a body, the class still can't be instantiated, why is that?
Pure virtual function can have a body, but the fact that you declare them pure virtual is exactly to say that a derived implementation is required.
You can execute the pure virtual method from a derived method (using an explicit BaseClass::method()) but still you have to provide an implementation.
Not being able to instantiate a class with a pure virtual method that has not been overriden is the main point of the pure virtual declaration. In other words the idea of declaring a method pure virtual is to ensure that the programmer will not forget about providing its implementation.
Generally speaking, abstract class is used to define interface and/or partial implementation, and is intended to be inherited by concrete classes. It is a way of enforcing a contract between class designer and users of that class, whatever they are.
If you don't need this contract and want instantiation, then do not enforce it to be abstract class, i.e. remove = 0.
If your concern is why would pure virtual functions have body in the first place, then one good example could be this quote from the Effective C++ book by Scott Meyers:
Derived classes that implement this pure virtual function may call
this implementation somewhere in their code. If part of the code of
two different derived classes is similar then it makes sense to move
it up in the hierarchy, even if the function should be pure virtual.
Another example is pure virtual destructor (which is also a function by the way):
...
virtual ~foo() = 0;
...
foo::~foo() {} // required!
when you are required to provide implementation for it, but at the same time want to make it pure virtual in order to make the foo class abstract. So, in fact, the core of the language itself relies on this feature.

How to declare a class explicity abstract?

I am looking at the following:
http://publib.boulder.ibm.com/infocenter/lnxpcomp/v8v101/index.jsp?topic=%2Fcom.ibm.xlcpp8l.doc%2Flanguage%2Fref%2Fcplr142.htm
and it says an abstract class in C++ contains a pure virtual function. However, surely this does not mean to create an abstract class all I do is insert a pure virtual function? Couldn't I have the situation where I have a concrete class which doesn't provide an implementation for one particular function and therefore makes it abstract, forcing derived classes to provide the implementation? This wouldn't make the class abstract though?
So how do I differentiate between "this is an abstract class" and "this is a concrete class with one pure virtual function"?
A class is extactly then abstract when it has one or more pure virtual function. If you write a (base) class, wich has all functions implemented, and thus can be instantiated, but it misses a vital function, then it is simply wrong design of your class.
Your base class wouldn't be complete in this case and the pure virtual uninmplemented function should be added, which makes it an abstract class then.
If you have a derived class, which derives from an abstract class, and doesn't implement all functions from the base class, then it is in turn also abstract. In this case, it wouldn't need a pure virtual function itself, because it is abstract by inheritance.
There is no abstract keyword in C++, like in Java to indicate that a class is abstract.
As already stated above, an abstract class in C++ is, by definition, a class which has at least one pure virtual function. The class being abstract means that you can't make instances of it (only of "concrete" classes derived from it), which protects you from calling the "unexistent" pure virtual functions (although technically you can still call them from base class constructor/destructor and get a nasty runtime crash).
There are no explicit "interface" kind of classes in C++, so you are free to provide implementation for some functions in any classes as you wish, regardless of whether the class is already abstract due to some other function being pure virtual.
On a side note, I'd still like to point out one way to make your class abstract without actually making any "real" methods pure virtual. It is enough to make the class destructor pure virtual (note that it is generally a good idea for the destructor of any polymorphic class to be virtual anyway). A minor gotcha here is that in this particular case (only for destructor), you will still have to provide an implementation for it for the linker to be happy. It may look like this:
class A // abstract class
{
public:
virtual ~A() = 0 {} // destructor is pure virtual, but still needs a body
};
class B : public A {}; // concrete class deriving from an abstract class
Also note that in this particular case, class B does not have to explicitly implement its own destructor to become concrete, so, if you'd like it to be abstract too, you'll have to repeat the same trick again (or add some other pure virtual methods to B).

C++ interfaces - what are my options?

Diving back into the world of C++, and experimenting with interfaces. I can find plenty of online examples, but 99% of them are trivial 'all-in-one-file'.
Interfaces can be classified into 3 basic types- interfaces where (all|some|zero) functions must be overridden in a concrete subclass (all|some|zero pure virtual functions in c++ parlance).
Is it possible to implement any of the 3 in a single header file? (no .cpp twin) Why/why not? How? If not, what are my options for the .h/.cpp pair?
Some of the options I have seen are: virtual destructor, protected destructor, inline destructor, pure virtual destructor with an implementation,... my head is spinning!
EDIT: meant pure virtual, not virtual void
If you make your interface pure virtual, the compiler will give an error if you forget to implement a method in your concrete class.
If there are methods that have some sane default implementation you can provide it, but this is just a convenience.
If you make the destructor virtual, you can delete the object via its interface pointer rather than requiring the concrete object pointer.
Herb Sutter has some interesting thoughts on interfaces which are at direct odds with the way most of us implement an interface: http://www.gotw.ca/publications/mill18.htm
Read this awesome piece of internet wisdom: http://www.parashift.com/c++-faq-lite/dtors.html
1) You never need a .cpp file, you can code all your programs in .h, but doing this is terrible style and will inevitabely slow your compilation.
MyClass : public MyInterface {
public:
virtual void myFunction() {
// override and implemenht
}
};
2) When inheriting classes you don't need to worry about declaring your destructor to be virtual, but you need to make sure that classes you are inheriting from have virtual destructors. Otherwise you might be faced with memory leaks. In so far as I know this is not necessary for interface classes with only pure virtual functions.
Destructor being inline makes no difference to you.
Destructor being declared as void is something that should give you a compiler error :).
Edit:
About the 3 types of interfaces, I am getting the sense that you are a little bit confused and this is hampering your googling.
An interface is usually a class that has no functions defined and you must inherit and implement all of them.
A class that has some functionality but still has some pure virtuals is usually called abstract.
When 'zero' functions must be overridden this is neither an interface nor an abstract class, it is just a plain old class that you can inherit and do whatever.
Check out the C++ faq.
Interface where all functions must be overridden by a concrete subclass is called interface
Interface where some functions must be overridden by a concrete subclass is called abstract class
Interface where zero functions must be overridden by a concrete subclass is called class.
You can implement virtual member functions inside header file. They will not inline though, because they have to have address to be placed into virtual table.
... my head is spinning!
To get it spinning more you can also have pure virtual destructor. This is useful trick when you want to have abstract class, but no real useful method to put pure virtual:
class A
{
public:
virtual ~A() = 0;
};
A::~A() {}
class B : public A
{
public:
~B() {}
};
Class A has destructor implemented, but it still can not be instantiated directly, because it is interface. Yet, when it comes to destroying B compiler has to obey to protocol and call ~A(). That is why you have to implement it

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)

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.