Inheritance and polymorphism

What is a difference between Inheritance and polymorphism?
Inheritance is when one class carries over functionality of another.
Polymorphism is when you refer to something as it's base class.

Inheritance
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
#include <iostream>

class Foo
{
   int Bar;
public:
   Foo(int x) : Bar(x) {}
   int GetBar(void) {return Bar;}
};

class Baz : public Foo
{
    int Foobar;
public:
    Baz(int x,int y) : Foo(x), Foobar(y) {}
    int GetFoobar(void) {return Foobar;}
    // Foo(x) calls the constructor of a Foo object that is
    // contained within this derived class (Baz)
};

// At this point, Foo contains an int and Baz contains
// an int and a Foo. Baz can also do everything Foo can: GetBar()

int main()
{
    Baz Fool(5,3);
    std::cout << Fool.GetBar() << std::endl;
    std::cout << Fool.GetFoobar() << std::endl;
}


Polymorphism
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
32
33
34
35
36
37
38
39
40
#include <iostream>
class Foo
{
   int Bar;
public:
   Foo(int x) : Bar(x) {}
   int GetBar(void) {return Bar;}
};

class Baz : public Foo
{
    int Foobar;
public:
    Baz(int x,int y) : Foo(x), Foobar(y) {}
    int GetFoobar(void) {return Foobar;}
};

int main()
{
    Foo Eric(5);
    Baz Bob(1,-12);
    Baz John(0,132);
    
    Foo * pFoo1 = &Eric; // pFoo1 points to the address of a Foo object
    Foo * pFoo2 = &Bob; // PFoo2 points to the address of a Baz object
    Foo * pFoo3 = &John; // pFoo3 points to the address of a Baz object
    
    std::cout << (pFoo1->GetBar()) << std::endl;
    // Uses a pointer to a foo to do the job (No polymorphism here)
    
    std::cout << (pFoo2->GetBar()) << std::endl;
    // Uses a pointer to a foo.. which stores a Baz.
    // The magic of Polymporhism tells the computer
    // that this Baz can be read as a Foo
    
    std::cout << (pFoo3->GetFoobar()) << std::endl;
    // The last line will produce an error or warning,
    // not all Foo's have a GetFoobar() member function,
    // however some can, it's unsafe to use it this way.
}

You might wonder, what is the use of polymorphism? When using stl containers (or even, boost containers) you can store groups of things, and read them as their base's. This means that you can define a class CShape; and make specializations of it: CTriangle, CSquare, CLine. They can all have the same member function names, but, depending on their derived type, they will all do something else.
Last edited on
Topic archived. No new replies allowed.