polymorphism

Pages: 12
polymorphism is roughly same with the inheritance,but they using virtual function and pure virtual function,what is the point of use the pure virtual function ?
Hi,

Google C++ Polymorphism

Hopefully you have already read this one:

http://www.cplusplus.com/doc/tutorial/polymorphism/


cplusplus wrote:
One of the key features of class inheritance 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.
Emphasis mine.

cplusplus wrote:
But an abstract base class is not totally useless. It can be used to create pointers to it, and take advantage of all its polymorphic abilities. For example, the following pointer declarations would be valid:

1
2
Polygon * ppoly1;
Polygon * ppoly2;


There are plenty of other articles to read when you look at Google.

human is sometimes explain more precise than a google
I'm pretty sure he didn't mean for you to ask a google bot, but to search on google where you will find plenty of human answers.
Take some time and look up polymorphism in more detail. It is one of the defining features of C++.
Take some time to look over what the others said.
Last edited on
your program is complicated leh,got static cast and dynamic cast
Hi all,

One really doesn't want or need to do casting to achieve polymorphism. I just want to point this out in a kind way to you JayhawkZombie :+)

This concept, which I quoted earlier is really important:

cplusplus wrote:
One of the key features of class inheritance 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.

Emphasis mine.

So the idea is to first create a base class that has pure virtual functions which form the interface to the classes.

Then create derived classes that re-implement those virtual functions, or re-implement them again to provide a specialisation for some branches of classes lower down in the inheritance tree.

Next, in main say, is to declare a container (std::vector say) of pointers to base class.

Then the important part: fill the container with pointers to various derived class objects. Note there is no conversion to a base class pointer. Nor is there a need for one to do this manually.

Now iterate through that container, using the pointers to call one of the interface functions. The compiler calls the correct function, even if it is a virtual function higher up the tree than the derived class. This is achieved by the compiler maintaining a vtable. This is where the compiler implicitly maintains pointers to each class' parent class. When a function call is made, the compiler looks first in the derived class, then successively in it's parent class' until it finds one. If there isn't a function with an implementation then it's an error.

The next big thing to realise, is to keep the naming of functions and classes general, in particular access (get) functions. By general, I mean not to have DogSpeak() and CatSpeak() functions, each one would just have Speak(). If this is done well enough, one might be able to get away with just having ordinary virtual functions (as opposed to pure) in the base class only. There could be some in derived classes too, to specialise; but the idea is to minimise the number of functions.

This works, even when the base class is abstract (has a pure virtual function) or is otherwise not capable of being instantiated (has a private constructors, say). This is again possible because of the quote above.

Imagine a base class called LivingThings, with derived classes for various types of animals and plants. If each class has access functions where the names of those functions are the same for each class: Species(), Genus(), etcetera. Now, provided that the values are set for each object, we can just use the base class interface via the derived object pointer, the compiler does the correct magic.

I can't emphasise how powerful this concept is. Another example: we don't have ConvertMetres(Feet* FeetValue) , instead we might have Convert(Unit* FromValue, Unit* ToValue). So one can see that we might have a few functions in a base class, instead of possibly hundreds spread around derived classes. One still has to re-implement the virtual function in each derived class to do a particular conversion, but the point is that the interface is small, as opposed to be massive.

Another concept is that of pushing functions and member data as high up the tree as possible, this helps to minimise the number of functions needed.

Also, consider that you may not need as many derived classes as what you might think. There may not be a need to have GermanShepard and Labrador classes, just have a Dog class. After all they probably store the same type of information, and probably don't have any particular specialisation. Avoiding specialisation by keeping things general where possible is a good idea.

Hopefully this is a suitably human answer for the OP :+)
Last edited on
Yes, I know. I merely wanted to show that you can cast it. I typically don't do any casting when I use polymorphism. I create derived objects and interface with them as if they were instantiated from the base class. And therein lies the power of it - all the derived properties remain.
@JayhawkZombie

Maybe the following is more of constructive criticism of your example, rather than your knowledge.

I merely wanted to show that you can cast it.


I would like to point out that use of a cast means one is not doing polymorphism properly. Most of your example was not IMO polymorphism, because you were using pointers to call a function in the same class. I would have liked to see an example of a function declared with a base pointer as a parameter. Or use of a container declared with base pointer.

In your example you said the pointers must be cast to base. That's not true, doing so doesn't achieve anything, just use the derived pointer, like you did prior. I find the idea of using an actual base pointer a little backwards: one specifically doesn't do that.

Also, I have a vague idea that using an actual base pointer causes object slicing like problems?





Also, I have a vague idea that using an actual base pointer causes object slicing like problems?

Nope. ;)
Then I will refrain from giving feedback on something that I clearly do not understand. I have removed my incorrect example.
@cire

My question was vague, maybe slicing is the wrong term? How about an actual base pointer not having access to a derived object's non virtual functions without a cast? Casting is what we are trying to avoid. Maybe there are other problems associated with doing this?

Anyway, I just use derived pointers as described above, and let the compiler do it's magic. As I understand it, doing otherwise defeats the purpose of polymorphism.

How about an actual base pointer not having access to a derived object's non virtual functions without a cast?

Yep!

Maybe there are other problems associated with doing this?

I'd say that was the main thing. Avoid throwing away type information unless you get some benefit from it.
Then I apologize for the very poor example. I will think future posts through more thoroughly and just avoid posting if I don't feel like I can come up with a good example that clearly conveys the concept.
Yep!


Yay !! :+D

Cheers!
> One of the key features of class inheritance 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.

Object-oriented techniques using classes and virtual functions are an important way to develop large, complex software applications and systems. So are generic programming techniques using templates. Both are important ways to express polymorphism – at run time and at compile time, respectively. And they work great together in C++. https://isocpp.org/wiki/faq/big-picture


Modern C++ incorporates two kinds of polymorphism: compile-time, through templates, and run-time, through inheritance and virtualization. You can mix the two kinds of polymorphism to great effect. The STL template shared_ptr uses internal virtual methods to accomplish its apparently effortless type erasure. But don't over-use virtualization for polymorphism when a template is the better choice. Templates can be very powerful.
https://msdn.microsoft.com/en-us/library/hh279654.aspx
microsoft wrote:
....... But don't over-use virtualization for polymorphism when a template is the better choice. Templates can be very powerful.


I like that part. I have been working providing my own class to be used with boost::units::quantity, so that I can have various named quantities (each with their own type) but with the same underlying quantity type, so that I can overload functions. This is a lot better than having lots of trivial structs or lots of inheritance.

I can start a new topic about this if anyone is interested.
why suddenly talk about STL containers already?why talk about pointer too? just tell me what is binding happen when compile,i really dont understand ==
@mike9407

I am worried that you might be trolling. I gave a pretty good explanation earlier, and you respond with questions like that and claim not to understand. Maybe English is not your first language? Do you use Google translate?

Maybe the questions you ask are too advanced for your knowledge so far? If you wonder why pointers are needed for polymorphism, then you have missed the very first key point, one which I quoted and emphasised twice.

All of your posts and replies are very short questions that can easily be Googled, I wonder if you have actually read any of them? I get the strong impression you are just trying waste everyone's time.

I only bothered to reply to any of your topics, because I wanted to set someone else straight.
You know, I don't know why I didn't just use my own project as an example of polymorphism. I even asked about smart pointers using polymorphism the other day. Why I didn't just pull from that is beyond me. Perhaps it's me recovering from a semester of C boot camp, or maybe my mind is fumbling with finals.

Say you have a base class, Base, and some classes that derive from it.
Polymorphism allows you to do this:
1
2
3
4
5
6
7
std::vector<Base *> myObejcts;

DerivedClass1 *derivedPtr1 = new DerivedClass1;
DerivedClass2 *derivedPtr2 = new DerivedClass2;

myObejcts.push_back(derivedPtr1);
myObjects.push_back(derivedPtr2);

This is exactly what I'm doing in my project.
You can push a pointer to any derived class into that vector, as long as that derived class derives from Base. Of course, make sure they actually point to an allocated object and not just garbage in memory.
You must use pointers to properly achieve this.
See this little stack overflow page about why pointers have to be used:
http://stackoverflow.com/questions/15188894/why-doesnt-polymorphism-work-without-pointers-references
That is all I will give code for, as you really need to try this yourself. There are many examples out there. A simple Google search will find you many.
See: http://www.cplusplus.com/doc/tutorial/polymorphism/

http://bfy.tw/3IfH

As I've recently learned, it is best to use smart pointers for this:
shared_ptr: http://en.cppreference.com/w/cpp/memory/shared_ptr
unique_ptr: http://en.cppreference.com/w/cpp/memory/unique_ptr
MSDN article on smart pointers: https://msdn.microsoft.com/en-us/library/hh279674.aspx
Smart pointers make memory management much less of a pain.
There are also other smart pointers. Look at them as well.

That should address:
...Or use of a container declared with base pointer.

What I did was do exactly that. A vector declared with a base class pointer, and I pushed derived class pointers into it. Of course, that is not the only way to take advantage of polymorphism. You can also pass a pointer of a derived class to a function that has a base class pointer as a parameter, for example.

My previous code was more of an example of inheritance than anything. If it showed any polymorphism, it was done poorly.
Despite what looks like stupidity in me, I cannot begin to describe how powerful polymorphism is. I do know what polymorphism is, so please pardon my malfunction. But thank you for also addressing it in a kind way instead of just ripping me to shreds. You all are much more respectful than my professors, who seem to have no problem insulting my intelligence. I spent time to clear up my mind and clear up concepts.
You will not do casting in polymorphism, as it defeats the purpose. That isn't to say that casting isn't ever useful, but only use it when it makes sense.

why suddenly talk about STL containers already?

STL containers are incredibly powerful tools, and provide great flexibility, not to mention everything else they do for you. They should be your default choice for containing objects.
Even if you don't fully understand templating, you should still learn how to use STL containers. I learned how to use them long before I learned how to make template classes.
See: http://www.cplusplus.com/reference/stl/

why talk about pointer too?

Polymorphism cannot be properly achieved without using pointers.
See my stack overflow page linked above.
Also See 'Obejct Slicing', something you'll want to avoid like the plague:
http://www.geeksforgeeks.org/object-slicing-in-c/
http://stackoverflow.com/questions/274626/what-is-object-slicing

@TheIdeasMan
I can start a new topic about this if anyone is interested.

Why don't you? OP might not want to see it, but I'd be very interested to see this. I've learned more here in the last two weeks than I did in half a semester in school (at least with C++, that is).

Perhaps this is me trying to salvage any credibility I may still have. Take it as you will. I can partially attribute this to being sent into C boot camp, and becoming somewhat distanced from C++, as well as a lack of thorough instruction from professors - I've since learned to check what they teach me for validity before asserting its truth. I've tried to be meticulous with this post to make sure I got it right, and addresses what was shown was wrong with my last code example. No more quickly typed-out responses from me, as we've seen what happens what I do that. I'll be much more meticulous with my posts and make sure I actually use the right concept.

OP: Read the articles and read the comments posted from others. They explain why pointers and STL containers are used, as well as other concepts you need to know. You can always use Google - it is your friend. How do you think I found the articles that I linked in here?

I had this typed up a little while ago, then clicked out of the box and hit 'Backspace'. Boom, it was gone. This website needs a 'Confirm' when you have stuff typed in the box and you try to leave the page before posting it. Now I'm copying my text every minute in case I do that again. Also, why 'polymorphism' isn't a recognized word baffles me.

Oops. Did it again. Glad I had that copied. No way I would have typed this out a third time.

TL;DR: There is none. Read the post, lazy.
Last edited on
Pages: 12