C++: Private virtual functions vs. pure virtual functions [duplicate] - c++

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Private virtual method in C++
If I understood correctly from this post (Private virtual method in C++), making a virtual function in a base class makes the derived classes able to override it. But it seems things stop there.
But if the base class virtual function is pure, that forces the derived classes to implement the function. Hence, a pure (public) virtual function is merely an interface. I can see a benefit here.
On the other hand, by making a base class virtual function private, only gives the derived class the ability to override the function, but I see no benefit of this. It's as if that private virtual function is not even there. The derived class obviously does not know about the existence of that virtual function in base class because its private, so is there any benefit of declaring a base class private function virtual, in term of inheritance or polymorphism?
Also, is there any situation where a base class would declare a function 'pure virtual' and 'private'?
Thank you.

One benefit is in implementing the template method pattern:
class Base {
public :
void doSomething() {
doSomething1();
doSomething2();
doSomething3();
}
private:
virtual void doSomething1()=0;
virtual void doSomething2()=0;
virtual void doSomething3()=0;
};
class Derived : public Base {
private:
virtual void doSomething1() { ... }
virtual void doSomething2() { .... }
virtual void doSomething3() { .... }
}
This allows the derived classes to implement each piece of a certain logic, while the base class determines how to put these pieces together. And since the pieces don't make sense by themselves, they are declared private and so hidden from client code.

It is for situations that base wants its children to implement functionality that the base itself needs to use. Imagine a silly example - cars.
class Car {
public:
int getTorque();
int getPower();
private:
virtual const Engine& gimmeEngine() = 0;
};
class Ferrari : public Car {
private:
FerrariEngine myCoolEngine;
const Engine& gimmeEngine() { return myCoolEngine; }
};
Now Car doesn't need to know anything about Ferrari's engine, only that it implements some Engine interface that guaranties that Car can get the information about its power and torque.
In this silly example everything could be simplified by making getTorque and getPower pure virtual, but I hope it illustrates the idea. Base needs to use some specific logic it knows every child must have, so it queries it throught a private pure virtual member.

If the method is virtual it can be overridden by derived classes, even if it's private. Anyway, it should be declared with protected.

Related

C++ Implement subclasses that extends subInterfaces without overriding already overriden methods

I created Interfaces (abstract classes) that expends other Interfaces in C++ and I tried to implement them but errors occur when I compile.
Here are the errors:
main.cpp: In function 'int main()':
main.cpp:36:38: error: cannot allocate an object of abstract type 'Subclass'
Subclass * subObj = new Subclass();
^
Subclass.h:13:7: note: because the following virtual functions are pure within 'Subclass':
class Subclass : SubInterface {
^
SuperInterface.h:13:18: note: virtual void SuperInterface::doSomething()
virtual void doSomething()=0;
Here are my sources:
#include <iostream>
class SuperInterface {
public:
virtual void doSomething() = 0;
protected:
int someValue;
};
class SubInterface : public SuperInterface {
public:
virtual void doSomethingElseThatHasNothingToDoWithTheOtherMethod() = 0;
protected:
int anotherValue;
};
class Superclass : public SuperInterface {
public:
Superclass() {}
virtual ~Superclass() {}
void doSomething() {std::cout << "hello stackoverflow!";}
};
class Subclass : public SubInterface {
public:
Subclass() {}
virtual ~Subclass() {}
void doSomethingElseThatHasNothingToDoWithTheOtherMethod() {std::cout << "goodbye stackoverflow!";}
};
int main(void)
{
Superclass * superObj = new Superclass();
Subclass * subObj = new Subclass();
}
Here's what I want:
I want my implementation to be aware and so have the same behaviour as of already overriden methods (e.g subObj->doSomething() method works without the need to implement it again). Can anyone tell me what I should do to make that happen if it's even possible? Thanks.
No, you can't do what you want through simple inheritance. At no point does Subclass inherit, or provide, an implementation of doSomething(), so you can't call subObj->doSomething() as you desire. You must honour the interface contract of subInterface.
You could inherit Subclass from Superclass and Subinterface, and just implement doSomething() as a kind of proxy, Superclass::doSomething(). You still need an implementation but you don't have to 're-implement' it.
You're getting the error because you're trying to create an object of an abstract class.
Your Subclass is an abstract class because of this line void doSomethingElse()=0;.
If a class has one pure virtual function, it will be an abstract class. You can't create an object of an abstract class, you can only have a reference or a pointer to it.
To get rid of the error, the declaration of doSomethingElse in Subclass should be
void doSomethingElse();
Instead of void doSomethingElse()=0;
Also I don't see why you need two interfaces. You could derive Subclass from the SuperInterface, as it is basically just the same as SubInterface
To be honest, I am not entirely sure what your design wants to express, but there are at least two technical errors here:
1.) You use private inheritance in all cases, so you do not actually deal with "interfaces" at all. Public inheritance is achieved like this:
class SubInterface : public SuperInterface
2.) You use =0 for a function you apparently want to implement.
This will fix the compiler errors, but the design is still questionable. Considering the motivation you gave at the end of your question, I recommend composition rather than (public) inheritance. In C++, to share functionality is best expressed with composition. To put it very brief, encapsulate the commonly used functionality in a separate class and equip the other classes with an object of it.
class CommonFunctionality
{
//...
public:
void doSomething();
void doSomethingElse();
};
class SuperClass
{
//...
private:
CommonFunctionality m_functionality;
};
class SubClass : public SuperClass
{
//...
private:
CommonFunctionality m_functionality;
};
In fact, perhaps you don't even need to create a class for CommonFunctionality. Perhaps simple free-standing functions would do. Programmers with a Java background (and your code looks a bit like it) tend to put too stuff into classes than what is necessary in C++.
Your class 'Subclass' should override 2 pure virtual methods, so:
class Subclass : SubInterface {
public:
Subclass();
virtual ~Subclass();
void doSomethingElse() override;
void doSomething() override;
};
by not doing so or stating
void doSomethingElse()=0;
class Subclass becomes abstract too, which cannot be instantiated. You could havea look at :http://www.parashift.com/c++-faq-lite/pure-virtual-fns.html
Here's what I want: I want my implementation to be aware and so have
the same behaviour as of already overriden methods (e.g
subObj->doSomething() method works without the need to implement it
again). Can anyone tell me what I should do to make that happen if
it's even possible!!?? Thanks.
--> maybe declare the methods virtual not pure virtual
There are 2 problems, which are clearly stated by compiler:
Problem 1
SubInterface::doSomethingElse()() in Subclass is declared as pure virtual, disregarding that you trying to define it in source file (I'm pretty sure, that this is a copy-paste kind of errors).
class Subclass : SubInterface
{
public:
Subclass();
virtual ~Subclass();
void doSomethingElse() = 0; // still pure?
};
Solution is obvious:
class Subclass : SubInterface
{
public:
Subclass();
virtual ~Subclass();
virtual void doSomethingElse() override
{
}
};
(here using C++11 override specifier, so compiler will check correctness of overriding; it is not obligatory)
Problem 2
doSomething() is not even tried to be overriden, neither in SuperInterface, nor in Subclass, so it stays pure virtual. Although doSomething() is overriden in Superclass, Subclass has no idea about existance of Superclass.
Solution: override doSomething() either in SuperInterface, or in Subclass, or in any of children of Subclass (don't have them yet). For example, overriding in Subclass:
class Subclass : SubInterface
{
public:
Subclass();
virtual ~Subclass();
virtual void doSomething() override
{
}
virtual void doSomethingElse() override
{
}
};
Other issues:
You are inheriting without visibility specifier, i.e. privately. Use public inheritance until you really need something else:
class Derved : public Base {};
Your source files have .c extension, but containing C++ code. This can confuse some compilers if you do not state programming language explicitly via command line arguments. By convention, most programmers use .cpp extension, and most compilers treat such files as C++ source files.

Virtual member functions in most-derived class?

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

Does it make any sense to define "pure" virtual functions in the base class itself?

The benefit of defining common virtual functions in the base class is that we don't have to redefine them in the derived classes then.
Even if we define pure virtual functions in the base class itself, we'll still have to define them in the derived classes too.
#include <iostream>
using namespace std;
class speciesFamily
{
public:
virtual void numberOfLegs () = 0;
};
void speciesFamily :: numberOfLegs ()
{
cout << "\nFour";
}
class catFamily : public speciesFamily
{
public:
void numberOfLegs ()
{
speciesFamily :: numberOfLegs ();
}
};
This may look fancy for sure, but are there any situations when it is beneficial to define a pure virtual function in the base class itself?
Two things:
First off, there's one border-line scenario which is commonly cited: Suppose you want an abstract base class, but you have no virtual functions to put into it. That means you have no functions to make pure-virtual. Now there's one way around: Since you always need a virtual destructor, you can make that one pure. But you also need an implementation, so that's your canditate:
struct EmptyAbstract
{
virtual ~EmptyAbstract() = 0; // force class to be abstract
};
EmptyAbstract::~EmptyAbstract() { } // but still make d'tor callable
This may help you minimize the implementation size of the abstract class. It's a micro-opimization somehow, but if it fits semantically, then it's good to have this option.
The second point is that you can always call base class functions from derived classes, so you may just want to have a "common" feature set, despite not wanting any abstract instances. Again, in come pure-virtual defined functions:
struct Base
{
virtual void foo() = 0;
};
struct Derived : Base
{
virtual void foo()
{
Base::foo(); // call common features
// do other stuff
}
};
void Base::foo() { /* common features here */ }
are there any situations when it is beneficial to define a pure virtual function in the base class itself?
Yes - if the function in question is the pure virtual destructor, it must also be defined by the base class.
A base-class with only pure virtual functions are what languages like Java would call an interface. It simply describes what functions are available, nothing else.
It can be beneficial when there is no reasonable implementation of pure virtual function can be in base class. In this case pure virtual functions are implemented in derived classes.

C++ Functions for an Abstract Base Class

Suppose I want to have an inheritance hierarchy like this.
class Base
class DerivedOne : public Base
class DerivedTwo : public Base
The base class is not meant to be instantiated, and thus has some pure virtual functions that the derived classes must define, making it an abstract base class.
However, there are some functions that you would like your derived classes to get from your base class. These functions modify private data members that both DerivedOne and DerivedTwo will have.
class Base {
public:
virtual void MustDefine() =0; // Function that derived classes must define
void UseThis(); // Function that derived classes are meant to use
};
However, the UseThis() function is meant to modify private data members. That's where the question comes in. Should I give the Base class dummy private data members? Should I give it protected data members (and thus the derived classes won't declare their own private data members). I know the second approach will decrease encapsulation.
What is the best approach to a situation like this? If a more detailed explanation is needed I'd be happy to provide it.
If those member variables are supposed to exist in all derived classes then you should declare them in the base class. If you are worried about encapsulation, you can make them private and provide protected accessor methods for derived classes.
Another five cents: the good practice is to have abstract interface class which has no other members, but only public pure virtual methods and often public virtual destructor. Then you create base implementation which can also be abstract but can have protected fields, etc.
In you case it would be something like:
class IBlaBla;
class BlaBlaBase : public IBlaBla;
class DerivedOne : public BlaBlaBase
class DerivedTwo : public BlaBlaBase
This allows you to have more flexibility in the future if you decide that Base is no longer good for some specialized task.
Should I give the Base class dummy
private data members?
If you can implement a part of functionality without exposing the details to the derived classes, then do it in base class. If your derived classes would need access to these members, provide setters and getters. However, it is not convenient to have setters available for derived classes because your code becomes tightly coupled.
Encapsulation is sometimes overrated. If your base class and derived classes need to access those members, then they should probably be protected, not private. If it really is something that needs to be encapsulated, then you may want to make them private but provide getters and setters (either make them private to Base, with getters and setters defined there, or private to the derived classes, with pure virtual getters and setters in Base).
It's a bit hard to give you more specific advice without knowing about the actual problem you're trying to solve.
You will have to define Base::UseThis(), in the body of which you will make use of Base's fields (which you will also need to declare in the class definition above). If you only need to access them in UseThis, they can be private. If DerivedOne/Two will need access to them, you should make them protected.
Here is a possible resolution to your dilemna:
class Base {
public:
virtual ~Base() {}
virtual void redefine_me() = 0;
void utility_function();
private:
virtual int get_data_member() = 0;
virtual void set_data_member(int v) = 0;
};
class Derived1 : public Base {
public:
virtual void redefine_me() { do_d1_stuff(); }
private:
int my_private_idaho_;
virtual int get_data_member() { return my_private_idaho_; }
virtual void set_data_member(int v) { my_rpviate_idaho_ = v; }
};
class Derived2 : public Base {
public:
virtual void redefine_me() { do_d2_stuff(); }
private:
int gomer_pyle_;
virtual int get_data_member() { return gomer_pyle_; }
virtual void set_data_member(int v) { gomer_pyle_ = v; }
};
void Base::utility_function()
{
set_data_member(get_data_member() + 1);
}
It's biggest disadvantage is that now access to the private data member is mediated by a virtual function call, which isn't the cheapest thing around. It's also hidden from the optimizer.
This means that if you choose it, you should adopt a pattern where you fetch the private data member into a local variable at the beginning of your utility function and set it from the local variable before you return. Of course some utility functions may call out to functions that require the object state to be updated before they're called, and this pattern would then have to be modified to account for that. But then again, such utility functions are likely not to be able to satisfy the strong exception handling guarantee and should be rethought anyway.
It looks as if you need some interface for client code, and some 'convenient' functionality for implementors of the interface, which they can only use if they follow the rule of calling the useThis function of the convenience layer, which will tweak their private members.
Whenever I gave in to the temptation of putting the convenience functionality in my abstract base class, I regretted it (soon!) afterwards. It takes away a lot of flexibility. The solution proposed by AlexKR makes this situation slightly better.
An alternative way of doing this is providing some convenience class that implementers of the interface can aggregate instead of inheriting it. It can provide a function taking the implementer's members as arguments.
class Interface { public: virtual void f() = 0; };
class Convenience {
public:
void tweakMyMembers( int& member1, float& member2 );
bool somestate;
};
class Implementor : public Interface {
int m1; float m2;
public: Implementor( bool b ): conv( b ) {}
virtual void f() { conv.tweakMyMembers( m1, m2 ); if( m1<m2 ) dothis(); }
};

Virtual/pure virtual explained

What exactly does it mean if a function is defined as virtual and is that the same as pure virtual?
From Wikipedia's Virtual function
...
In object-oriented programming, in languages such as C++, and Object Pascal, a virtual function or virtual method is an inheritable and overridable function or method for which dynamic dispatch is facilitated. This concept is an important part of the (runtime) polymorphism portion of object-oriented programming (OOP). In short, a virtual function defines a target function to be executed, but the target might not be known at compile time.
Unlike a non-virtual function, when a virtual function is overridden the most-derived version is used at all levels of the class hierarchy, rather than just the level at which it was created. Therefore if one method of the base class calls a virtual method, the version defined in the derived class will be used instead of the version defined in the base class.
This is in contrast to non-virtual functions, which can still be overridden in a derived class, but the "new" version will only be used by the derived class and below, but will not change the functionality of the base class at all.
whereas..
A pure virtual function or pure virtual method is a virtual function that is required to be implemented by a derived class if the derived class is not abstract.
When a pure virtual method exists, the class is "abstract" and can not be instantiated on its own. Instead, a derived class that implements the pure-virtual method(s) must be used. A pure-virtual isn't defined in the base-class at all, so a derived class must define it, or that derived class is also abstract, and can not be instantiated. Only a class that has no abstract methods can be instantiated.
A virtual provides a way to override the functionality of the base class, and a pure-virtual requires it.
I'd like to comment on Wikipedia's definition of virtual, as repeated by several here. [At the time this answer was written,] Wikipedia defined a virtual method as one that can be overridden in subclasses. [Fortunately, Wikipedia has been edited since, and it now explains this correctly.] That is incorrect: any method, not just virtual ones, can be overridden in subclasses. What virtual does is to give you polymorphism, that is, the ability to select at run-time the most-derived override of a method.
Consider the following code:
#include <iostream>
using namespace std;
class Base {
public:
void NonVirtual() {
cout << "Base NonVirtual called.\n";
}
virtual void Virtual() {
cout << "Base Virtual called.\n";
}
};
class Derived : public Base {
public:
void NonVirtual() {
cout << "Derived NonVirtual called.\n";
}
void Virtual() {
cout << "Derived Virtual called.\n";
}
};
int main() {
Base* bBase = new Base();
Base* bDerived = new Derived();
bBase->NonVirtual();
bBase->Virtual();
bDerived->NonVirtual();
bDerived->Virtual();
}
What is the output of this program?
Base NonVirtual called.
Base Virtual called.
Base NonVirtual called.
Derived Virtual called.
Derived overrides every method of Base: not just the virtual one, but also the non-virtual.
We see that when you have a Base-pointer-to-Derived (bDerived), calling NonVirtual calls the Base class implementation. This is resolved at compile-time: the compiler sees that bDerived is a Base*, that NonVirtual is not virtual, so it does the resolution on class Base.
However, calling Virtual calls the Derived class implementation. Because of the keyword virtual, the selection of the method happens at run-time, not compile-time. What happens here at compile-time is that the compiler sees that this is a Base*, and that it's calling a virtual method, so it insert a call to the vtable instead of class Base. This vtable is instantiated at run-time, hence the run-time resolution to the most-derived override.
I hope this wasn't too confusing. In short, any method can be overridden, but only virtual methods give you polymorphism, that is, run-time selection of the most derived override. In practice, however, overriding a non-virtual method is considered bad practice and rarely used, so many people (including whoever wrote that Wikipedia article) think that only virtual methods can be overridden.
The virtual keyword gives C++ its' ability to support polymorphism. When you have a pointer to an object of some class such as:
class Animal
{
public:
virtual int GetNumberOfLegs() = 0;
};
class Duck : public Animal
{
public:
int GetNumberOfLegs() { return 2; }
};
class Horse : public Animal
{
public:
int GetNumberOfLegs() { return 4; }
};
void SomeFunction(Animal * pAnimal)
{
cout << pAnimal->GetNumberOfLegs();
}
In this (silly) example, the GetNumberOfLegs() function returns the appropriate number based on the class of the object that it is called for.
Now, consider the function 'SomeFunction'. It doesn't care what type of animal object is passed to it, as long as it is derived from Animal. The compiler will automagically cast any Animal-derived class to a Animal as it is a base class.
If we do this:
Duck d;
SomeFunction(&d);
it'd output '2'. If we do this:
Horse h;
SomeFunction(&h);
it'd output '4'. We can't do this:
Animal a;
SomeFunction(&a);
because it won't compile due to the GetNumberOfLegs() virtual function being pure, which means it must be implemented by deriving classes (subclasses).
Pure Virtual Functions are mostly used to define:
a) abstract classes
These are base classes where you have to derive from them and then implement the pure virtual functions.
b) interfaces
These are 'empty' classes where all functions are pure virtual and hence you have to derive and then implement all of the functions.
In a C++ class, virtual is the keyword which designates that, a method can be overridden (i.e. implemented by) a subclass. For example:
class Shape
{
public:
Shape();
virtual ~Shape();
std::string getName() // not overridable
{
return m_name;
}
void setName( const std::string& name ) // not overridable
{
m_name = name;
}
protected:
virtual void initShape() // overridable
{
setName("Generic Shape");
}
private:
std::string m_name;
};
In this case a subclass can override the the initShape function to do some specialized work:
class Square : public Shape
{
public:
Square();
virtual ~Square();
protected:
virtual void initShape() // override the Shape::initShape function
{
setName("Square");
}
}
The term pure virtual refers to virtual functions that need to be implemented by a subclass and have not been implemented by the base class. You designate a method as pure virtual by using the virtual keyword and adding a =0 at the end of the method declaration.
So, if you wanted to make Shape::initShape pure virtual you would do the following:
class Shape
{
...
virtual void initShape() = 0; // pure virtual method
...
};
By adding a pure virtual method to your class you make the class an abstract base class
which is very handy for separating interfaces from implementation.
"Virtual" means that the method may be overridden in subclasses, but has an directly-callable implementation in the base class. "Pure virtual" means it is a virtual method with no directly-callable implementation. Such a method must be overridden at least once in the inheritance hierarchy -- if a class has any unimplemented virtual methods, objects of that class cannot be constructed and compilation will fail.
#quark points out that pure-virtual methods can have an implementation, but as pure-virtual methods must be overridden, the default implementation can't be directly called. Here is an example of a pure-virtual method with a default:
#include <cstdio>
class A {
public:
virtual void Hello() = 0;
};
void A::Hello() {
printf("A::Hello\n");
}
class B : public A {
public:
void Hello() {
printf("B::Hello\n");
A::Hello();
}
};
int main() {
/* Prints:
B::Hello
A::Hello
*/
B b;
b.Hello();
return 0;
}
According to comments, whether or not compilation will fail is compiler-specific. In GCC 4.3.3 at least, it won't compile:
class A {
public:
virtual void Hello() = 0;
};
int main()
{
A a;
return 0;
}
Output:
$ g++ -c virt.cpp
virt.cpp: In function ‘int main()’:
virt.cpp:8: error: cannot declare variable ‘a’ to be of abstract type ‘A’
virt.cpp:1: note: because the following virtual functions are pure within ‘A’:
virt.cpp:3: note: virtual void A::Hello()
A virtual function is a member function that is declared in a base class and that is redefined by derived class. Virtual function are hierarchical in order of inheritance.
When a derived class does not override a virtual function, the function defined within its base class is used.
A pure virtual function is one that contains no definition relative to the base class.
It has no implementation in the base class. Any derived class must override this function.
How does the virtual keyword work?
Assume that Man is a base class, Indian is derived from man.
Class Man
{
public:
virtual void do_work()
{}
}
Class Indian : public Man
{
public:
void do_work()
{}
}
Declaring do_work() as virtual simply means: which do_work() to call will be determined ONLY at run-time.
Suppose I do,
Man *man;
man = new Indian();
man->do_work(); // Indian's do work is only called.
If virtual is not used, the same is statically determined or statically bound by the compiler, depending on what object is calling. So if an object of Man calls do_work(), Man's do_work() is called EVEN THOUGH IT POINTS TO AN INDIAN OBJECT
I believe that the top voted answer is misleading - Any method whether or not virtual can have an overridden implementation in the derived class. With specific reference to C++ the correct difference is run-time (when virtual is used) binding and compile-time (when virtual is not used but a method is overridden and a base pointer is pointed at a derived object) binding of associated functions.
There seems to be another misleading comment that says,
"Justin, 'pure virtual' is just a term (not a keyword, see my answer
below) used to mean "this function cannot be implemented by the base
class."
THIS IS WRONG!
Purely virtual functions can also have a body AND CAN BE IMPLEMENTED! The truth is that an abstract class' pure virtual function can be called statically! Two very good authors are Bjarne Stroustrup and Stan Lippman.... because they wrote the language.
Simula, C++, and C#, which use static method binding by default, the programmer can specify that particular methods should use dynamic binding by labeling them as virtual.
Dynamic method binding is central to object-oriented programming.
Object oriented programming requires three fundamental concepts: encapsulation, inheritance, and dynamic method binding.
Encapsulation allows the implementation details of an
abstraction to be hidden behind a
simple interface.
Inheritance allows a new abstraction to be defined as an
extension or refinement of some
existing abstraction, obtaining some
or all of its characteristics
automatically.
Dynamic method binding allows the new abstraction to display its new
behavior even when used in a context
that expects the old abstraction.
Virtual methods CAN be overridden by deriving classes, but need an implementation in the base class (the one that will be overridden)
Pure virtual methods have no implementation the base class. They need to be defined by derived classes. (So technically overridden is not the right term, because there's nothing to override).
Virtual corresponds to the default java behaviour, when the derived class overrides a method of the base class.
Pure Virtual methods correspond to the behaviour of abstract methods within abstract classes. And a class that only contains pure virtual methods and constants would be the cpp-pendant to an Interface.
Pure Virtual Function
try this code
#include <iostream>
using namespace std;
class aClassWithPureVirtualFunction
{
public:
virtual void sayHellow()=0;
};
class anotherClass:aClassWithPureVirtualFunction
{
public:
void sayHellow()
{
cout<<"hellow World";
}
};
int main()
{
//aClassWithPureVirtualFunction virtualObject;
/*
This not possible to create object of a class that contain pure virtual function
*/
anotherClass object;
object.sayHellow();
}
In class anotherClass remove the function sayHellow and run the code. you will get error!Because when a class contain a pure virtual function, no object can be created from that class and it is inherited then its derived class must implement that function.
Virtual function
try another code
#include <iostream>
using namespace std;
class aClassWithPureVirtualFunction
{
public:
virtual void sayHellow()
{
cout<<"from base\n";
}
};
class anotherClass:public aClassWithPureVirtualFunction
{
public:
void sayHellow()
{
cout<<"from derived \n";
}
};
int main()
{
aClassWithPureVirtualFunction *baseObject=new aClassWithPureVirtualFunction;
baseObject->sayHellow();///call base one
baseObject=new anotherClass;
baseObject->sayHellow();////call the derived one!
}
Here the sayHellow function is marked as virtual in base class.It say the compiler that try searching the function in derived class and implement the function.If not found then execute the base one.Thanks
"A virtual function or virtual method is a function or method whose behavior can be overridden within an inheriting class by a function with the same signature" - wikipedia
This is not a good explanation for virtual functions. Because, even if a member is not virtual, inheriting classes can override it. You can try and see it yourself.
The difference shows itself when a function take a base class as a parameter. When you give an inheriting class as the input, that function uses the base class implementation of the overriden function. However, if that function is virtual, it uses the one that is implemented in the deriving class.
Virtual functions must have a definition in base class and also in derived class but not necessary, for example ToString() or toString() function is a Virtual so you can provide your own implementation by overriding it in user-defined class(es).
Virtual functions are declared and defined in normal class.
Pure virtual function must be declared ending with "= 0" and it can only be declared in abstract class.
An abstract class having a pure virtual function(s) cannot have a definition(s) of that pure virtual functions, so it implies that implementation must be provided in class(es) that derived from that abstract class.