Solved

21. Explain the principle of polymorphism.

Posted on 2015-01-24
2
51 Views
Last Modified: 2015-02-11
Explain the principle of polymorphism.
Provide examples.
0
Comment
Question by:Nusrat Nuriyev
2 Comments
 
LVL 86

Assisted Solution

by:jkr
jkr earned 250 total points
Comment Utility
Polymorphism is the concept of accessing objects through pointers to common base classes. This allows to define a common interface for a group of classes that have common traits, e.g.

class Vehicle {
public:
  virtual void Drive() {speed = 0;}
protected:
  int speed;
};

class Bicycle: public Vehicle {
public:
  virtual void Drive() {speed = 10;}
};

class Car: public Vehicle {
public:
  virtual void Drive() {speed = 50;}
};

void Race(Vehicle** vehicles, size_t count) {

  for (size_t i = 0; i < count; ++i) {

    vehicles[i]->Drive();
  }
}
int main () {

  Car car;
  Bicycle bike;

  Vehicle* arr[] = { &car, &bike};

  Race(arr, 2);

  return 0;
}

Open in new window



You will find another nice example at http://www.cplusplus.com/doc/tutorial/polymorphism/
0
 
LVL 32

Accepted Solution

by:
phoffric earned 250 total points
Comment Utility
Just wanted you to be aware of static vs. dynamic polymorphism.
http://www.cpptutor.com/static-polymorphism-and-dynamic-polymorphism-in-c++.htm
http://en.wikipedia.org/wiki/Template_metaprogramming#Static_polymorphism

You have two identical function names, but they go to different functions - polymorphism. If the compiler can call the function directly - that's static polymorphism. If it cannot, and the correct function is only known at runtime - that's dynamic polymorphism.
0

Featured Post

Threat Intelligence Starter Resources

Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

Join & Write a Comment

C++ Properties One feature missing from standard C++ that you will find in many other Object Oriented Programming languages is something called a Property (http://www.experts-exchange.com/Programming/Languages/CPP/A_3912-Object-Properties-in-C.ht…
Many modern programming languages support the concept of a property -- a class member that combines characteristics of both a data member and a method.  These are sometimes called "smart fields" because you can add logic that is applied automaticall…
The viewer will learn how to clear a vector as well as how to detect empty vectors in C++.
The viewer will be introduced to the member functions push_back and pop_back of the vector class. The video will teach the difference between the two as well as how to use each one along with its functionality.

762 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now