< C++ Virtual Function 1 | Main | C++ Formatted I/O 1 >| Site Index | Download >


 

 

 

 

 

MODULE 17a - C++ POLYMORPHISM CODE SAMPLES 2

 

 

 

 

 

 

 

My Training Period: xx hours

 

The source code for this tutorial is available in C++ Polymorphism source code.

 

17.7    C++ Pointer Rule

  • A pointer declared as pointing to a base class can be used to point to an object of a derived class of that base class, but a pointer to a derived class cannot be used to point to an object of the base class or to any of the other derived classes of the base class.

  • In our program therefore, we are allowed to declare a pointer to the vehicle class which is the base class, and use that pointer to refer to objects of the base class or any of the derived classes.

  • This is exactly what we do in the main() program. We define a single pointer which points to the vehicle class and use it to point to objects of each of the classes in the same order as in the last four programs. In each case, we allocate the object, send a message to the method named message() and de-allocate the object before going on to the next class.

  • You will notice that when we send the four messages, we are sending the message to the same method, named message() which is a part of the vehicle base class. This is because the pointer has a class associated with it. Even though the pointer is actually pointing to four different classes in this program, the program acts as if the pointer is always pointing to an object of the base class because the pointer is the base class type.

17.8    An Actual Virtual Function

  • We finally come to a program example with a virtual function that operates as a virtual function and exhibits dynamic binding or polymorphism as it is called.

1.     // program poly6.cpp

2.     #include  <iostream>

3.     using namespace std;

4.      

5.     // a base class declaration

6.     // and the implementation part

7.     class   vehicle

8.     {

9.           int    wheels;

10.         float  weight;

11.         public:

12.             virtual void  message(void)

13.             // first message() method, with virtual keyword

14.             {cout<<"Vehicle message, from vehicle, the base class\n";}

15.  };

16.   

17.  // a derived class declaration and implementation part

18.  class  car : public  vehicle

19.  {

20.         int   passenger_load;

21.         public:

22.             void   message(void)    // second message()

23.             {cout<<"Car message, from car, the vehicle derived class\n";}

24.  };

25.   

26.  class  truck : public  vehicle

27.  {

28.         int  passenger_load;

29.         float   payload;

30.         public:

31.             int  passengers(void) {return  passenger_load;}

32.  };

33.   

34.  class  boat : public  vehicle

35.  {

36.         int  passenger_load;

37.         public:

38.             int  passengers(void) {return  passenger_load;}

39.             void  message(void)     // third message()

40.             {cout<<"Boat message, from boat, the vehicle derived class\n";}

41.  };

42.   

43.  // the main program

44.  int   main()

45.  {

46.   

47.      cout<<"Re add the virtual keyword. Using\n";

48.      cout<<"pointer variables, new and\n";

49.      cout<<"delete keyword\n";

50.      cout<<"-----------------------------------\n";

51.   

52.      vehicle  *unicycle;

53.   

54.     unicycle = new vehicle;

55.     unicycle->message();

56.        delete unicycle;

57.     unicycle = new car;

58.     unicycle->message();

59.            delete unicycle;

60.     unicycle = new truck;

61.     unicycle->message();

62.            delete unicycle;

63.   

64.     unicycle = new boat;

65.     unicycle->message();

66.            delete unicycle;

67.   

68.    cout<<"\nThe real virtual function huh!\n";

69.   

70.    // system("pause");

71.    return  0;

72.  }

 

72 Lines: Output:

 

C++ Polymorphism and virtual function

  • Notice that the structure of the virtual function in the base class and each of the derived classes is identical. The return type and the number and types of the parameters must be identical for all functions, since a single statement can be used to call any of them.

  • If the keyword virtual is used, the system will use late binding (some call it dynamic Binding) which is done at run time, but if the keyword is not included, early binding (some call it static binding) will be used. What these words actually mean is that with late binding, the compiler does not know which method will actually respond to the message because the type of the pointer is not known at compile time. With early binding, however, the compiler decides at compile time what method will respond to the message sent to the pointer.

  • In real world, the example for the late binding is when the application program calling the DLL (dynamic link library) file(s) during the program execution.  The DLL files don’t have the main() function and it can be called (shared) by many programs.

  • Compile and run this program example.

 

More Program Example And Experiment

 

// polymorphic functions, virtual keyword program example...

#include <iostream>

using namespace std;

 

// class declaration and implementation - the base class

class Shape

{

       // protected member variables should be available for derived classes...

       protected:

           char* Color;

      

       public:

           // constructor, set the object's data

           Shape(){Color = "No Color!";}

           ~Shape(){};

           // virtual base member function...

           // return the object's data

           virtual char* GetColor(){return Color;}

};

 

// derived class...

class Rectangle:public Shape

{

       // notice the same variable name, it is OK...

       char* Color;      

       public:

           Rectangle(){Color = "bLue SkY!";}

           ~Rectangle(){ }

           // derived class member function

           // should also be virtual...

           char* GetColor(){return Color;}

};

 

class Square:public Shape

{

       char* Color;

       public:

           Square(){ Color = "yEllOw!";}

           ~Square(){ }

           char* GetColor(){return Color;}

};

 

class Triangle:public Shape

{

       char* Color;

       public:

           Triangle(){Color = "GrEEn!";}

           ~Triangle(){ }

           char* GetColor(){return Color;}

};

 

class Circle:public Shape

{

       char* Color;

       public:

           Circle(){Color = "aMbEr!";}

           ~Circle(){ }

           // let set different function name but

           // same functionality...

           char* GetMyColor(){return Color;}

};

 

// the main program

int main()

{

       // instantiate objects of ... class type

       Shape ObjOne;

       Rectangle ObjTwo;

       Square ObjThree;

       Triangle ObjFour;

       Circle ObjFive;

 

       cout<<"Non polymorphic, early binding:"<<endl;

       cout<<"----------------------------------"<<endl;

       cout<<"Shape color:     "<<ObjOne.GetColor()<<endl;

       cout<<"Rectangle color: "<<ObjTwo.GetColor()<<endl;

       cout<<"Square color:    "<<ObjThree.GetColor()<<endl;

       cout<<"Triangle color:  "<<ObjFour.GetColor()<<endl;

       // notice the different function name as previous function...

       cout<<"Circle color:    "<<ObjFive.GetMyColor()<<endl;

 

       cout<<"\nPolymorphic, late binding:"<<endl;

       cout<<"--------------------------"<<endl;    

 

       // pointer variable of type Shape class...

       Shape *VirtualPtr;

 

       // object allocation of type Shape size...

       VirtualPtr = new Shape;

       cout<<"Shape color:     "<<VirtualPtr->GetColor()<<endl;

       cout<<"  VirtualPtr pointer reference   = "<<VirtualPtr<<endl;

       // de-allocate, clean up...

       delete VirtualPtr;

 

       VirtualPtr = new Rectangle;

       cout<<"Rectangle color: "<<VirtualPtr->GetColor()<<endl;

       cout<<"  VirtualPtr pointer reference   = "<<VirtualPtr<<endl;

       delete VirtualPtr;

 

       VirtualPtr = new Square;

       cout<<"Square color:    "<<VirtualPtr->GetColor()<<endl;

       cout<<"  VirtualPtr pointer reference   = "<<VirtualPtr<<endl;

       delete VirtualPtr;

 

       VirtualPtr = new Triangle;

       cout<<"Triangle color:  "<<VirtualPtr->GetColor()<<endl;

       cout<<"  VirtualPtr pointer reference   = "<<VirtualPtr<<endl;

       delete VirtualPtr;

 

       // no GetColor() in this derived class, so use the GetColor from the base class...

       VirtualPtr = new Circle;

       cout<<"Circle color:    "<<VirtualPtr->GetColor()<<endl;

       cout<<"  VirtualPtr pointer reference   = "<<&VirtualPtr<<"\n\n";

       delete VirtualPtr;

 

       // retest..

       VirtualPtr = new Triangle;

       cout<<"Triangle color:  "<<VirtualPtr->GetColor()<<endl;

       cout<<"  VirtualPtr pointer reference   = "<<VirtualPtr<<endl;

       delete VirtualPtr;

 

       return 0;

}

 

Output:

 

C++ Polymorphism and virtual function

// program poly6.cpp

#include  <iostream>

using namespace std;

 

// a base class declaration, and implementation part

class   vehicle

{

   int    wheels;

   float  weight;

   public:

       virtual void  message(void)

       // first message() method, with virtual keyword

       {cout<<"Vehicle message, from vehicle, the base class\n";}

};

 

// derived class declaration and implementation part

class  car : public  vehicle

{

   int   passenger_load;

   public:

       void   message(void)    // second message()

       {cout<<"Car message, from car, the vehicle derived class\n";}

};

    

class  truck : public  vehicle

{

   int  passenger_load;

   float   payload;

   public:

       int  passengers(void) {return  passenger_load;}

};

    

class  boat : public  vehicle

{

   int  passenger_load;

   public:

       int  passengers(void) {return  passenger_load;}

       void  message(void)     // third message()

       {cout<<"Boat message, from boat, the vehicle derived class\n";}

};

    

// the main program

int   main()

{

    cout<<"Re add the virtual keyword. Using\n";

    cout<<"  pointer variables, new and\n";

    cout<<"       delete keyword\n";

    cout<<"==================================\n";

 

     vehicle  *unicycle;

 

   unicycle = new vehicle;

   unicycle->message();

      delete unicycle;

   unicycle = new car;

   unicycle->message();

        delete unicycle;

   unicycle = new truck;

   unicycle->message();

        delete unicycle;

 

   unicycle = new boat;

   unicycle->message();

        delete unicycle;

 

  cout<<"\nThe real virtual function huh!\n";

  cout<<"==================================\n";

 

  return 0;

}

 

Output:

 

 

 

 

 

 

 

 

 

 

 

 

C++ polymorphism - a virtual functions program example compiled using Visual C++ .NET

///////-polymorph.cpp-/////////

///////-polymorphic functions, virtual function-////////

///////-FEDORA 3, g++ x.x.x-///////

#include <iostream>

using namespace std;

 

// a class declaration and implementation, a base class

class Shape

{

        // protected member variables should be available for derived classes...

        protected:

            char* Color;

       

        public:

            // constructor, set the object's data

            Shape(){Color = "No Color!";}

            ~Shape(){};

            // virtual base member function...

            // return the object's data

            virtual char* GetColor(){return Color;}

};

 

// derived class...

class Rectangle:public Shape

{

        // notice the same variable name, it is OK...

        char* Color;

        public:

            Rectangle(){Color = "bLue SkY!";}

            ~Rectangle(){}

            // derived class member function

            // should also be virtual...

            char* GetColor(){return Color;}

};

 

class Square:public Shape

{

        char* Color;

        public:

            Square(){Color = "yEllOw!";}

            ~Square(){}

            char* GetColor(){return Color;}

};

 

class Triangle:public Shape

{

        char* Color;

        public:

            Triangle(){Color = "GrEEn!";}

            ~Triangle(){}

            char* GetColor(){return Color;}

};

 

class Circle:public Shape

{

        char* Color;

        public:

            Circle(){Color = "aMbEr!";}

            ~Circle(){}

            // let set different function name but

            // same functionality...

            char* GetMyColor(){return Color;}

};

 

// the main program

int main()

{

        // instantiate objects of class type...

        Shape ObjOne;

        Rectangle ObjTwo;

        Square ObjThree;

        Triangle ObjFour;

        Circle ObjFive;

 

        cout<<"Non polymorphic, early binding:"<<endl;

        cout<<"----------------------------------"<<endl;

        cout<<"Shape color:     "<<ObjOne.GetColor()<<".  ";

        cout<<" The address-->"<<&ObjOne<<endl;

        cout<<"Rectangle color: "<<ObjTwo.GetColor()<<". ";

        cout<<" The address-->"<<&ObjTwo<<endl;

        cout<<"Square color:    "<<ObjThree.GetColor()<<". ";

        cout<<" The address-->"<<&ObjThree<<endl;

        cout<<"Triangle color:  "<<ObjFour.GetColor()<<". ";

        cout<<" The address-->"<<&ObjFour<<endl;

        // notice the different function name as previous function...

        cout<<"Circle color:    "<<ObjFive.GetMyColor()<<". ";

        cout<<"The address-->"<<&ObjFive<<endl;

 

        cout<<"\nPolymorphic, late binding:"<<endl;

        cout<<"--------------------------"<<endl;

 

        // pointer variable of type Shape class...

        Shape *VirtualPtr;

 

        // object allocation of type Shape size...

        VirtualPtr = new Shape;

        cout<<"Shape color:     "<<VirtualPtr->GetColor()<<endl;

        cout<<"  VirtualPtr pointer reference   = "<<VirtualPtr<<endl;

        // de-allocate, clean up...

        delete VirtualPtr;

 

        VirtualPtr = new Rectangle;

        cout<<"Rectangle color: "<<VirtualPtr->GetColor()<<endl;

        cout<<"  VirtualPtr pointer reference   = "<<VirtualPtr<<endl;

        delete VirtualPtr;

 

        VirtualPtr = new Square;

        cout<<"Square color:    "<<VirtualPtr->GetColor()<<endl;

        cout<<"  VirtualPtr pointer reference   = "<<VirtualPtr<<endl;

        delete VirtualPtr;

 

        VirtualPtr = new Triangle;

        cout<<"Triangle color:  "<<VirtualPtr->GetColor()<<endl;

        cout<<"  VirtualPtr pointer reference   = "<<VirtualPtr<<endl;

        delete VirtualPtr;

 

        // no GetColor() in this derived class, so use the GetColor from the base class...

        VirtualPtr = new Circle;

        cout<<"Circle color:    "<<VirtualPtr->GetColor()<<endl;

        cout<<"  VirtualPtr pointer reference   = "<<&VirtualPtr<<"\n\n";

        delete VirtualPtr;

 

        // retest...

        VirtualPtr = new Triangle;

        cout<<"Triangle color:  "<<VirtualPtr->GetColor()<<endl;

        cout<<"  VirtualPtr pointer reference   = "<<VirtualPtr<<endl;

        delete VirtualPtr;

 

        return 0;

}

 

[bodo@bakawali ~]$ g++ polymorph.cpp -o polymorph

[bodo@bakawali ~]$ ./polymorph

 

Non polymorphic, early binding:

----------------------------------

Shape color:     No Color!.   The address-->0xbffffa80

Rectangle color: bLue SkY!.  The address-->0xbffffa70

Square color:    yEllOw!.  The address-->0xbffffa60

Triangle color:  GrEEn!.  The address-->0xbffffa50

Circle color:    aMbEr!. The address-->0xbffffa40

 

Polymorphic, late binding:

--------------------------

Shape color:     No Color!

  VirtualPtr pointer reference   = 0x804b008

Rectangle color: bLue SkY!

  VirtualPtr pointer reference   = 0x804b008

Square color:    yEllOw!

  VirtualPtr pointer reference   = 0x804b008

Triangle color:  GrEEn!

  VirtualPtr pointer reference   = 0x804b008

Circle color:    No Color!

  VirtualPtr pointer reference   = 0xbffffa3c

 

Triangle color:  GrEEn!

VirtualPtr pointer reference   = 0x804b008

 

 

tenouk C++ polymorphism code and program examples

 

 

 

 

 

 

 

 

 

 

 

 

Further C++ Polymorphism related reading:

 

  1. Visual C++ .NET programming tutorial.

  2. The source code for this tutorial is available in C++ Polymorphism source code.

  3. Check the best selling C/C++, Object Oriented and pattern analysis books at Amazon.com.

 

 

 

 

 

|< C++ Virtual Function 1 | Main | C++ Formatted I/O 1 >| Site Index | Download |


C++ Polymorphism-virtual function:  Part 1 | Part 2