difference between polymorphism and overloading - c++

I found there has many definition about polymorphism and overloading. Some people said that overloading is one type of polymorphism. While some people said they are not the same. Because only one function will be allocate in overloading. While the polymorphism need allocate the memory for each redefined member function. I really feel confusion about this, any one could explain this for me?
Further, whether overloading happens at compile time while the polymorphism happens at running time?

Polymorphism is the process to define more than one body for functions/methods with same name.
Overloading IS a type of polymorphism, where the signature part must be different. Overriding is another, that is used in case of inheritance where signature part is also same.
No, it's not true that polymorphism happens in runtime. What happens in runtime is called runtime polymorphism. That is implemented using virtual keyword in C++.
Hope it helped..

The polymorphism is the base of the OOP, the overloading is one of ways to implement to polymorphism, specially when are involved operators. More generally, speaking about polymorphism when there are two or more classes involved. While the overloading can be made also inside the same class, we can overload the name of a method with several signatures (different list of parameters). While overriding is designed exclusively for involving two or more classes. Note that the overrided methods have all the same signature.

this was told by Bjarne Stroustrup in his book,polymorphism is one which a single thing that act in many forms (i.e) A single function that act in many forms with different parameters. since in c++ constructor name have to be same as class name, you cant have different constructors with different name. so to overcome that function overloading came. many people confuse that function overloading is a type of of polymorphism. they are both at different ends they cant be tied together.

You cannot determine whether a method is a polymorphic method, or simply an overridden method based solely upon its signature. You need to see how the method is invoked.
Here is some sample code which may help illuminate the answer:
public class parentClass {
//Overridden method
public void disp()
{
System.out.println("Output: disp() method of parent class");
}
}
public class childClass extends parentClass {
//You cannot determine whether these methods are polymorphic
//or static polymorphic (aka overridden) simply by their signatures.
//It is by the way they are invoked which determines this.
public void disp(){
System.out.println(" Output: disp() method of Child class");
}
public long add(long a, long b){
return a + b;
}
public int add(int a, int b){
return a+b;
}
public String add(String a, String b){
return a + b;
}
public static void main( String args[]) {
//Here a child class has overridden the disp() method of the
//parent class. When a child class reference refers to the child
//class overriding method this is known as static polymorphism
//or more simply, overriding.
System.out.println("childClass referencing the childClass's overridden, or static polymorphic method");
childClass myChildObj = new childClass();
myChildObj.disp();
//Another example of static polymorphic, or overridden methods
System.out.println("The following are overridden, or static polymorphic methods:");
System.out.printf(" Long add()override method results: %d \n",
myChildObj.add(5999999, 1));
System.out.printf(" Integer add() override method results: %d \n", myChildObj.add(3,2));
System.out.printf(" String add() override method results: %s \n",
myChildObj.add(" First and ...", " Second"));
//When the parent class reference refers to the child class object
//then the overriding method is called.
//This is called dynamic method dispatch and runtime polymorphism
System.out.println("True polymorphism, when the parent class object calls the child class's method:");
parentClass myParentObj = new childClass();
myParentObj.disp();
}
}
The expected output:
childClass referencing the childClass's overridden, or static polymorphic method
Output: disp() method of Child class
The following are overridden, or static polymorphic methods:
Long add()override method results: 6000000
Integer add() override method results: 5
String add() override method results: First and ... Second
One example of true polymorphism, when the parent class object calls the child class's method:
Output: disp() method of Child class

The word itself exlains the clear meaning. 'Poly' means multiple, while 'morphism' (used in image technology) means the process of gradual change from one form to another. Thus, same thing will have different forms.
Technically, Polymorphism is way of implementing 'Single Interface (Skeleton or structure) multiple Implementation (content or body)'. Polymorphism is a general term which refers to both overloading and overriding. Overloading is done in same class where the functions or methods with the same name have different signatures (argument list or return type) while overriding comes in picture in case of inheritance where a function interface, in the Super class, has similar interface in the subclass and has different implementation than the one in super class.
The Super class and sub class form a hierarchy moving from lesser specialization to greater specialization and this should always be remembered while implementing overriding of functions.

Function overloading takes place with functions having same name, but with different parameters.
In polymorphism the functions having same name are chosen based on its objects.

Polymorphism is based on following 2 concepts:
Overloading(Compile-Time polymorphism): Methods with same name but different operation
Overriding(Run-Time polymorphism): Override a method in base class by creating similar method in derived class
-Corrected the Explainations
Shyam Kodase

Overloading is just a way of providing multiple ways of calling the same method/function/constructor with default values, less arguments etc.
Polymorphism is about object inheritance, sub classes etc.

Related

Can a derived class redefine virtual function with a function of different signature?

There is somewhat odd sample given in one of the Microsoft documentation pages , which consists of two classes, one is a base class and another one is a derived. The base class has the following virtual function member:
virtual void setEars(string type) // virtual function
{
_earType = type;
}
And another, defined in the derived class, which, as stated in comments, redefines the virtual function:
// virtual function redefined
void setEars(string length, string type)
{
_earLength = length;
_earType = type;
}
These two have different signatures and I haven't ever heard if you actually can redefine a virtual function with a function of a different signature. I compiled this sample and could find any overriding behavior between these two. Is the sample just misleading or I'm missing something?
Is the sample just misleading or I'm missing something?
This example is indeed misleading.
When overriding a virtual function in a derived type, it must come with the same signature as it is defined in the base class. If that is not the case, the function in the child class will be considered as its own entity and is not considered in a polymorphic function call. Additionally, it will hide the name of the base classes function, which is considered bad practice, as it violates the "is-a" relationship in public inheritance.
In order to prevent such accidental hiding, C++ introduced the override keyword. When overriding a virtual function, it then must have a matching signature, otherwise, the compiler will reject it.

Why must we declare virtual methods as such

Suppose we have a class, "Animal", and subclasses, "Cat" and "Dog".
Let's say we want to allow both "Cat" and "Dog" to make a noise (cat: "meow" - dog: "woof") when we pass their objects into an intermediate function for any "Animal".
Why must we use a virtual method to do this? Couldn't we just do Animal->makeNoise() without defining a virtual method in "Animal"? As "Cat" and "Dog" are both animals, wouldn't it be clear that "makeNoise()" is referring to the Animal which has been passed to the function?
Is this just a matter of syntax or something more? I'm pretty sure in Java we don't have to do this.
In Java, all member functions are virtual by default (except static, private, and final ones).
In C++, all member functions are non-virtual by default. Making functions virtual adds overhead - both runtime and to object size - and the C++ philosophy is don't pay for what you don't use. Most of my objects are not polymorphic, so I shouldn't have to pay for polymorphism unless I need it. Since you need Animal::makeNoise() to be virtual, you must explicitly specify it as such.
C++ is designed to run with as little overhead as possible, trusting the programmer to make the correct call. Essentially, it 'gives you the gun and the option to shoot yourself in the foot', as one of my friends likes to say often. Speed and flexibility are paramount.
To correctly cause true polymorphic behavior, C++ requires it be specified. However! It is only required to be specified in the base class, as all derived class will inherit the virtual member functions. If a member inherits a virtual member function, it is good practice to place 'virtual' in the declaration, but not required.
ADTs usually implement pure virtual functions to indicate that the derived classes MUST implement the function. Such as:
animal makeNoise() = 0; /*Indicates this function contains no implementation.
and must be implemented by derived classes in order to function.*/
Again, it is not required the derived classes include 'virtual' in their inherited members so long as the base class includes this.
If you want to deduce the type of the Animal and then call make_sound(), then you would have to do a dynamic_cast on the animal object for each and every child of animal. This would include any class that is directly or indirectly a child of the Animal class.
This is both difficult to maintain and very painful to any change eg. Adding new class as a child to the Animal class.
Since c++ philosophy is efficiency, you will have to ask the compiler to provide you with run-time polymorphism as it is costly. How would you do that? By stating the make_sound() function as virtual. This creates a vtable ( a table of functions pointers ) which refers to an address of make_sound() which differs to based on the type of the object.
No need to downcast as indirection handles everything for you. What could be hundreds of lines of code is just a single line of code. That is the power of indirection!!
You could say that you have to do it because that's one of the rules of the language.
There's a reason its helpful though.
When trying to validate the code that uses an Animal, the complier knows what functions exist on an Animal. Its possible to tell whether the code is correct without checking all classes that derive from animal. So that code doesn't need to depend on all those derived classes. If you derive a new class from Animal but forget to implement the makeNoise function that's an error in the new class not the code that uses the Animal base class and the complier can point you towards that error. Without the virtual function declared in Animal there would no way to tell if its the calling code or the new class that is in error.
A key point here is that these errors would be caught at compile-time for C++ because of its static typing. Other languages can allow dynamic typing, which can make some things easier but, the errors would only be spotted at runtime.
In Java, all functions are virtual by default. In C++ they are not, so when you call a non-virtual function on a pointer of a given type, that type's implementation of that function is invoked with the object's address as this.
class Animal {
public:
void sound() { std::cout << "splat\n"; }
virtual void appearance() { std::cout << "animaly\n"; }
};
class Cat {
public:
void sound() { std::cout << "meow\n"; }
virtual void appearance() { std::cout << "furry\n"; }
};
int main() {
Animal a;
Cat c;
Animal* ac = new Cat;
a.sound(); // splat
a.appearance(); // animaly
c.sound(); // meow
c.appearance(); // furry
ac->sound(); // splat
ac->appearance(); // furry
}
This would occur when you wanted to write a function that generalized on "Animal" rather than requiring a specific derived class pointer.
In java you use virtual methods too.
It improves the loosely coupling of your software.
For example, you can use a library and don't know which animal they use internally. There is a animal implementation you don't know and you can use it because it's an animal. You get the animal with a library.getAnimal method. Now you can use their animal without to know which noise it makes, because they have to implement the method makeNoise.
Edit: So to answer your question, c++ wants a explicit declaration and in java it is implicit. so yes it is a kind of language specific idiosyncracy.

Virtual methods in constructor

Calling virtual methods in C++ is prohibited, however there are a few situations, where it might be very useful.
Consider the following situation - pair of Parent and Child classes. Parent constructor requires a Child class to be instantiated, because it has to initialize it in a special way. Both Parent and Child may be derived, such that DerivedParent uses DerivedChild.
There's a problem, however - because in Parent::ctor call from DerivedParent::ctor, base class should have an instance of DerivedChild instead of Child. But that would require calling a virtual method some way, what is prohibited. I'm talking about something like this:
class Child
{
public:
virtual std::string ToString() { return "Child"; }
};
class DerivedChild : public Child
{
public:
std::string ToString() { return "DerivedChild"; }
};
class Parent
{
protected:
Child * child;
virtual Child * CreateChild() { return new Child(); }
public:
Parent() { child = CreateChild(); }
Child * GetChild() { return child; }
};
class DerivedParent : public Parent
{
protected:
Child * CreateChild() { return new DerivedChild(); }
};
int main(int argc, char * argv[])
{
DerivedParent parent;
printf("%s\n", parent.GetChild()->ToString().c_str());
getchar();
return 0;
}
Let's get a real-world example. Suppose, that I want to write wrapper for WinApi's windows. The base Control class should register class and instantiate a window (eg. RegisterClassEx and CreateWindowEx), to properly set it up (for example register class in such way, that window structure has additional data for class instance; set up generic WndProc for all Controls; put reference to this by SetWindowLongPtr etc.)
On the other hand, derived class should be able to specify styles and extended styles, class name for window etc.
If constructing instance of window in the Control's constructor is a contract to be fulfilled, I see no other solution than to use VMs in ctor (what won't work).
Possible workarounds:
Use static polymorphism (eg. class Derived : public Base), but it will not work, if one wants to derive from Derived;
Pass a lambda from derived to base ctor if it is possible - it will work, but it's a total hardcore solution;
Pass a ton of parameters from derived to base ctor - it shall work, but won't be neither elegant, nor easy to use.
I personally don't like neither of them. Out of curiosity, I checked, how the problem is solved in Delphi's VCL, and you know what, base class calls CreateParams, which is virtual (Delphi allows such calls and guarantees, that they are safe - class fields are initialized to 0 upon creating).
How can one overcome this language restriction?
Edit: In response to answers:
Call CreateChild from the derived constructor. You're already requiring CreateChild to be defined, so this is an incremental step. You can add a protected: void init() function in the base class to keep such initialization encapsulated.
It will work, but it's not an option - quoting the famous C++ FAQ:
The first variation is simplest initially, though the code that actually wants to create objects requires a tiny bit of programmer self-discipline, which in practice means you're doomed. Seriously, if there are only one or two places that actually create objects of this hierarchy, the programmer self-discipline is quite localized and shouldn't cause problems.
Use CRTP. Make the base class a template, have the child supply the DerivedType, and call the constructor that way. This kind of design can sometimes eliminate virtual functions completely.
It's not an option, because it will work only once, for base class and its immediate descendant.
Make the child pointer a constructor argument, for example to a factory function.
This is, so far, the best solution - injecting code into base ctor. In my case, I won't even need to do it, because I can just parametrize base ctor and pass values from the descendant. But it will actually work.
Use a factory function template to generate the child pointer of the appropriate type before returning a parent. This eliminates the complexity of a class template. Use a type traits pattern to group child and parent classes.
Yea, but it has some drawbacks:
Someone, who derives from my classes may publish his ctor and bypass the security measures;
It would prevent one from using references, one would have to use smart pointers.
Calling virtual methods in C++ is prohibited, however there are a few situations, where it might be very useful.
No, calling a virtual method in the constructor dispatches to the most-derived complete object, which is the one under construction. It's not prohibited, it's well-defined and it does the only thing that would make sense.
A C++ base class is not allowed to know the identity of the most derived object, for better or worse. Under the model, the derived object doesn't start to exist until after the base constructors have run, so there's nothing to get type information about.
Some alternatives in your case are:
Call CreateChild from the derived constructor. You're already requiring CreateChild to be defined, so this is an incremental step. You can add a protected: void init() function in the base class to keep such initialization encapsulated.
Use CRTP. Make the base class a template, have the child supply the DerivedType, and call the constructor that way. This kind of design can sometimes eliminate virtual functions completely.
Make the child pointer a constructor argument, for example to a factory function.
Use a factory function template to generate the child pointer of the appropriate type before returning a parent. This eliminates the complexity of a class template. Use a type traits pattern to group child and parent classes.

Differentiate between function overloading and function overriding

Differentiate between function overloading and function overriding in C++?
Overloading a method (or function) in C++ is the ability for functions of the same name to be defined as long as these methods have different signatures (different set of parameters). Method overriding is the ability of the inherited class rewriting the virtual method of the base class.
a) In overloading, there is a relationship between methods available in the same class whereas in overriding, there a is relationship between a superclass method and subclass method.
(b) Overloading does not block inheritance from the superclass whereas overriding blocks inheritance from the superclass.
(c) In overloading, separate methods share the same name whereas in overriding, subclass method replaces the superclass.
(d) Overloading must have different method signatures whereas overriding must have same signature.
Function overloading is done when you want to have the same function with different parameters
void Print(string s);//Print string
void Print(int i);//Print integer
Function overriding is done to give a different meaning to the function in the base class
class Stream//A stream of bytes
{
public virtual void Read();//read bytes
}
class FileStream:Stream//derived class
{
public override void Read();//read bytes from a file
}
class NetworkStream:Stream//derived class
{
public override void Read();//read bytes from a network
}
You are putting in place an overloading when you change the original types for the arguments in the signature of a method.
You are putting in place an overriding when you change the original Implementation of a method in a derived class.
Overriding means, giving a different definition of an existing function with same parameters,
and overloading means adding a different definition of an existing function with different parameters.
Example:
#include <iostream>
class base{
public:
//this needs to be virtual to be overridden in derived class
virtual void show(){std::cout<<"I am base";}
//this is overloaded function of the previous one
void show(int x){std::cout<<"\nI am overloaded";}
};
class derived:public base{
public:
//the base version of this function is being overridden
void show(){std::cout<<"I am derived (overridden)";}
};
int main(){
base* b;
derived d;
b=&d;
b->show(); //this will call the derived overriden version
b->show(6); // this will call the base overloaded function
}
Output:
I am derived (overridden)
I am overloaded
1.Function Overloading is when multiple function with same name exist in a class.
Function Overriding is when function have same prototype in base class as well as derived class.
2.Function Overloading can occur without inheritance.
Function Overriding occurs when one class is inherited from another class.
3.Overloaded functions must differ in either number of parameters or type of parameters should be different.
In Overridden function parameters must be same.
For more detail you can visit below link where you get more information about function overloading and overriding in c++
https://googleweblight.com/i?u=https://www.geeksforgeeks.org/function-overloading-vs-function-overriding-in-cpp/&hl=en-IN
Function overloading is same name function but different arguments. Function over riding means same name function and same as arguments
Function overloading - functions with same name, but different number of arguments
Function overriding - concept of inheritance. Functions with same name and same number of arguments. Here the second function is said to have overridden the first
in overloading function with same name having different parameters whereas in overridding function having same name as well as same parameters replace the base class to the derived class (inherited class)
Function overloading may have different return types whereas function overriding must have same or matching return types.
Overloading means having methods with same name but different signature
Overriding means rewriting the virtual method of the base class.............
In addition to the existing answers, Overridden functions are in different scopes; whereas overloaded functions are in same scope.

Why use base class pointers for derived classes

class base{
.....
virtual void function1();
virtual void function2();
};
class derived::public base{
int function1();
int function2();
};
int main()
{
derived d;
base *b = &d;
int k = b->function1() // Why use this instead of the following line?
int k = d.function1(); // With this, the need for virtual functions is gone, right?
}
I am not a CompSci engineer and I would like to know this. Why use virtual functions if we can avoid base class pointers?
The power of polymorphism isn't really apparent in your simple example, but if you extend it a bit it might become clearer.
class vehicle{
.....
virtual int getEmission();
}
class car : public vehicle{
int getEmission();
}
class bus : public vehicle{
int getEmission();
}
int main()
{
car a;
car b;
car c;
bus d;
bus e;
vehicle *traffic[]={&a,&b,&c,&d,&e};
int totalEmission=0;
for(int i=0;i<5;i++)
{
totalEmission+=traffic[i]->getEmission();
}
}
This lets you iterate through a list of pointers and have different methods get called depending on the underlying type. Basically it lets you write code where you don't need to know what the child type is at compile time, but the code will perform the right function anyway.
You're correct, if you have an object you don't need to refer to it via a pointer. You also don't need a virtual destructor when the object will be destroyed as the type it was created.
The utility comes when you get a pointer to an object from another piece of code, and you don't really know what the most derived type is. You can have two or more derived types built on the same base, and have a function that returns a pointer to the base type. Virtual functions will allow you to use the pointer without worrying about which derived type you're using, until it's time to destroy the object. The virtual destructor will destroy the object without you knowing which derived class it corresponds to.
Here's the simplest example of using virtual functions:
base *b = new derived;
b->function1();
delete b;
its to implement polymorphism. Unless you have base class pointer
pointing to derived object you cannot have polymorphism here.
One of the key features of derived classes is that a pointer to a
derived class is type-compatible with a pointer to its base class.
Polymorphism is the art of taking advantage of this simple but
powerful and versatile feature, that brings Object Oriented
Methodologies to its full potential.
In C++, a special type/subtype relationship exists in which a base
class pointer or a reference can address any of its derived class
subtypes without programmer intervention. This ability to manipulate
more than one type with a pointer or a reference to a base class is
spoken of as polymorphism.
Subtype polymorphism allows us to write the kernel of our application
independent of the individual types we wish to manipulate. Rather, we
program the public interface of the base class of our abstraction
through base class pointers and references. At run-time, the actual
type being referenced is resolved and the appropriate instance of the
public interface is invoked. The run-time resolution of the
appropriate function to invoke is termed dynamic binding (by default,
functions are resolved statically at compile-time). In C++, dynamic
binding is supported through a mechanism referred to as class virtual
functions. Subtype polymorphism through inheritance and dynamic
binding provide the foundation for objectoriented programming
The primary benefit of an inheritance hierarchy is that we can program
to the public interface of the abstract base class rather than to the
individual types that form its inheritance hierarchy, in this way
shielding our code from changes in that hierarchy. We define eval(),
for example, as a public virtual function of the abstract Query base
class. By writing code such as
_rop->eval();
user code is shielded from the variety and volatility of our query language. This not only allows for the addition, revision,
or removal of types without requiring changes to user programs, but
frees the provider of a new query type from having to recode behavior
or actions common to all types in the hierarchy itself. This is
supported by two special characteristics of inheritance: polymorphism
and dynamic binding. When we speak of polymorphism within C++, we
primarily mean the ability of a pointer or a reference of a base class
to address any of its derived classes. For example, if we define a
nonmember function eval() as follows, // pquery can address any of the
classes derived from Query
void eval( const Query *pquery ) { pquery->eval(); }
we can invoke it legally, passing in the address of an object of any of the
four query types:
int main()
{
AndQuery aq;
NotQuery notq;
OrQuery *oq = new OrQuery;
NameQuery nq( "Botticelli" ); // ok: each is derived from Query
// compiler converts to base class automatically
eval( &aq );
eval( &notq );
eval( oq );
eval( &nq );
}
whereas an attempt to invoke eval() with the address of an object not derived from Query
results in a compile-time error:
int main()
{ string name("Scooby-Doo" ); // error: string is not derived from Query
eval( &name);
}
Within eval(), the execution of pquery->eval(); must invoke the
appropriate eval() virtual member function based on the actual class
object pquery addresses. In the previous example, pquery in turn
addresses an AndQuery object, a NotQuery object, an OrQuery object,
and a NameQuery object. At each invocation point during the execution
of our program, the actual class type addressed by pquery is
determined, and the appropriate eval() instance is called. Dynamic
binding is the mechanism through which this is accomplished.
In the object-oriented paradigm, the programmer manipulates an unknown instance of a bound but infinite set of types. (The set of
types is bound by its inheritance hierarchy. In theory, however, there
is no limit to the depth and breadth of that hierarchy.) In C++ this
is achieved through the manipulation of objects through base class
pointers and references only. In the object-based paradigm, the
programmer
manipulates an instance of a fixed, singular type that is completely defined at the point of compilation. Although the
polymorphic manipulation of an object requires that the object be
accessed either through a pointer or a reference, the manipulation of
a pointer or a reference in C++ does not in itself necessarily result
in polymorphism. For example, consider
// no polymorphism
int *pi;
// no language-supported polymorphism
void *pvi;
// ok: pquery may address any Query derivation
Query *pquery;
In C++, polymorphism
exists only within individual class hierarchies. Pointers of type
void* can be described as polymorphic, but they are without explicit
language support — that is, they must be managed by the programmer
through explicit casts and some form of discriminant that keeps track
of the actual type being addressed.
You seem to have asked two questions (in the title and in the end):
Why use base class pointers for derived classes?
This is the very use of polymorphism. It allows you to treat objects uniformly while allowing you to have specific implementation. If this bothers you, then I assume you should ask: Why polymorphism?
Why use virtual destructors if we can avoid base class pointers?
The problem here is you cannot always avoid base class pointers to exploit the strength of polymorphism.