Need help understanding how to polymorph

I just went to the tutorials but i still have a hard time understanding how to polymorph.

From what i understand so far, polymorphing is basically a function that accepts a class object in its parameters and in the body of the function, you can call any function from the object and display any member. Please correct me if i'm wrong

1
2
3
4
5
6
7
8
void polymorph (Rottweiler & object1)   //Rottweiler is the name of a class
 {
    object1.displayData();

    object1.displayMembers();

 }


The code segment above is part of another program that I am doing. Is that how you polymorph?
Last edited on
Does this help??

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
28
29
30
31
#include <iostream>
class Animal {
public:
    virtual void speak() = 0;
};

class Cat : public Animal {
public:
    void speak() {
        printf("Meow");
    }
};

class Dog : public Animal {
public:
    void speak() {
        printf("Woof");
    }
};
int main(int argc, const char * argv[])
{
    Dog merlin;
    Cat peaches;

    merlin.speak();
    std::cout << std::endl;
    peaches.speak();

    return 0;
}


output

1
2
Woof
Meow


I would read here
http://www.cplusplus.com/doc/tutorial/polymorphism/


There are other ways to use polymorphism but the above code is how I understand one of it's uses.

Last edited on
ok so basically, the right time to use virtual functions is when you have 2 functions that have the same return type, name and parameter list in both derived and base classes, right?. And you use virtual functions so that the compiler knows which function to call?
Hi,

One really handy thing is the ability to make functions take a reference or pointer to a base class as an parameter, then one sends it a reference to a derived class as an argument. The code does the right thing : it knows which derived function to call because it has a derived class reference, but the beauty is that it can greatly reduce how many functions one needs. By having a virtual or pure virtual function high up in the inheritance tree, one can greatly reduce the number of functions required lower down in the tree.

Here is an example about making pies, that I wrote awhile back:


http://www.cplusplus.com/forum/beginner/144603/#msg762560


Hope all goes well.
Topic archived. No new replies allowed.