Is it polymorphism

I wrote program to create polymorphism using function overloading, I know we can create polymorphism using function overloading operator overloading, method overriding and virtual functions, etc.

first I tried to create polymorphism using function overloading
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
 #include <iostream>
#include <string>
using namespace std;

class Vehicle {
  public:
    void Vehicles() {
      cout << "vehicles\n" ;
    }
};

class SportCar : public Vehicle {
  public:
    void Vehicles () {
      cout << "Sport player Use sport Car\n" ;
    }
};

int main() {
  Vehicle mycar;
  SportCar jaguar;
 
  mycar.Vehicles();
  jaguar.Vehicles();
 
  return 0;
}

Is it polymorphism ?
Polymorphism is, if an object of type derived-class gets used as it where of type base class.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <iostream>
#include <string>
using namespace std;

class Vehicle {
  public:
    virtual void Vehicles() {
      cout << "vehicles\n" ;
    }
    virtual ~Vehicle() {}
};

class SportCar : public Vehicle {
  public:
    void Vehicles () override {
      cout << "Sport player Use sport Car\n" ;
    }
};

int main() {
    
  Vehicle * myCar = new SportCar();
 
  myCar->Vehicles();
 
  delete myCar;
}

At this example, the real object is of type SportCar, but it is used as if it would be of type Vehicle.
We can now invoke all methods whose methods would be defined at the base-class, but these methods get substituted by the methods of the derived object if they are declared as virtual.

*edit syntax error
Last edited on
Function overloading is compile-time polymorphism; the behaviour is decided when writing the code.

Both a and b are vectors, have different type and hence behaviour:
1
2
3
4
5
std::vector<int> a;
std::vector<std::string> b;

std::cout << a[0]; // calls the int version of <<
std::cout << b[0]; // calls the string version of << 


The factory returns an object that depends on input data. The true type is determined during runtime.
1
2
3
4
5
int main() {
  Vehicle * myCar = factory();
  myCar->accelerate();
  delete myCar;
}

All vehicles can accelerate, but a truck, sport car, and Tardis do it differently.
Correct me if I'm wrong and I am sure somebody will but it seems that we need to distinguish between polymorphism which relates to functions and inheritance which relates to classes.

A seemingly erudite exposition of the topic is documented at http://techdifferences.com/difference-between-inheritance-and-polymorphism.html

@sahay143 appears to me to describe inheritance rather than polymorphism. But unfortunately it is not a definitively good example whereby the difference is made clear.

Also: http://www.cplusplus.com/doc/tutorial/polymorphism/
There's probably an article on inheritance too.

Now for the onslaught!


Registered users can post here. Sign in or register to post.