|< C++ Data Encapsulation 5 | Main | C++ Data Encapsulation 7 >| Site Index | Download |


 

 

 

 

 

MODULE 13b

C++ OBJECTS & CLASSES - ENCAPSULATION CODE EXAMPLES 6

 

 

 

 

My Training Period: xx hours

 

This is a continuation from the previous Module. The source code for this tutorial is available in C++ Data Encapsulation source code.

 

The C++ programming abilities that should be acquired: Able to understand and use:

 

 

 

 

13.12    Operator Overloading

  • Examine the program named opverlod.cpp carefully; this program contains examples of operators overloading.  This allows you to define a class of objects and redefine the use of the normal operators.

1.     // program opverlod.cpp, operator overloading

2.     #include <iostream>

3.     using namespace std;

4.      

5.     // a class declaration part

6.     class   wall

7.     {

8.            public:

9.            int   length;

10.          int   width;

11.         

12.          public:

13.              void   set(int l, int w)  {length = l; width = w;}

14.              int   get_area(void)  {return length * width;}

15.              // operator overloading

16.              friend wall operator + (wall aa, wall bb);   // add two walls

17.              friend wall operator + (int aa, wall bb);     // add a constant to a wall

18.              friend wall operator * (int aa, wall bb);

19.              // multiply a wall by a constant

20.      };

21.     

22.      // class implementation part

23.      wall operator + (wall aa, wall bb)

24.      // add two walls widths together

25.     {

26.          wall  temp;

27.          temp.length = aa.length;

28.          temp.width = aa.width + bb.width;

29.          return  temp;

30.       }

31.      

32.       wall operator + (int aa, wall bb)

33.       // add a constant to wall

34.       {

35.           wall  temp;

36.           temp.length = bb.length;

37.           temp.width = aa + bb.width;

38.           return  temp;

39.        }

40.       

41.        wall operator * (int aa, wall bb)

42.        // multiply wall by a constant

43.        {

44.            wall  temp;

45.            temp.length = aa * bb.length;

46.            temp.width = aa * bb.width;

47.            return  temp;

48.         }

49.        

50.         void  main()

51.        {

52.               wall   small, medium, large;   //object instances

53.               wall   temp;

54.              

55.               small.set(2,4);

56.               medium.set(5,6);

57.               large.set(8,10);

58.              

59.               cout<<"Normal values\n";

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

61.               cout<<"Area of the small wall surface is "<<small.get_area()<<"\n";

62.               cout<<"Area of the medium wall surface is "<<medium.get_area()<<"\n";

63.               cout<<"Area of the large wall surface is "<<large.get_area()<<"\n\n";

64.               cout<<"Overload the operators!"<<"\n";

65.               cout<<"-----------------------"<<endl;

66.               temp = small + medium;

67.               cout<<"New value-->2 * (4 + 6)\n";

68.               cout<<"New area of the small wall surface is "<<temp.get_area()<<"\n\n";

69.               cout<<"New value-->2 * (10 + 4) \n";

70.               temp = 10 + small;

71.               cout<<"New area of the medium wall surface is "<<temp.get_area()<<"\n\n";

72.               cout<<"New value-->(4 * 8) * (4 * 10)\n";

73.               temp = 4 * large;

74.               cout<<"New area of the large wall surface is "<<temp.get_area()<<"\n\n";

75.              

76.               // system("pause");

77.     }

 

77 lines: Output:

 

C++ object and class operator overloading program examples

friend wall operator + (wall aa, wall bb);      // add two walls

friend wall operator + (int aa, wall bb);         // add a constant to a wall

friend wall operator * (int aa, wall bb);

object1 + object2

object1.operator + (object2)

int.operator + (object)

wall operator + (wall aa, wall bb)

{

      wall  temp;

      temp.length = aa.length;

      temp.width = aa.width + bb.width;

      return  temp;

}

temp = small + medium;

 

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

 

Infix Expression: Any expression in the standard form such as "4*2-6/3" is an Infix (In order) expression.

 

Postfix Expression: The Postfix (Post order) form of the above expression is "42*63/-".

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

temp = 10 + small;

temp = 4 * large;

 

 

 

 

 

 

 

 

 

 

 

 

Operators

+

-

*

/

%

^

&

|

~

!

=

<

>

+=

-=

*=

/=

%=

^=

&=

|=

<<

>>

>>=

<<=

==

!=

<=

>=

&&

||

++

--

->*

,

[  ]

( )

new

delete

 

Table 13.1: Operators that can be overloaded

 

Operators

.

.*

?:

::

 

Table 13.2:  Operators that cannot be overloaded

 

13.13    Function Overloading

1.            // program funovlod.cpp, function overloading

2.            #include <iostream>

3.            using namespace std;

4.             

5.            // a class declaration part

6.            class many_names

7.            {

8.                int   length;

9.                int   width;

10.             public:

11.                 many_names(void); 

12.                 many_names(int len);

13.                 many_names(int len, int wid);

14.                 // constructors with different number and type

15.                 // of parameter list – overloaded functions

16.                 void display(void);

17.                 void display(int one);

18.                 void display(int one, int two);

19.                 void display(float number);

20.                 // methods with different number and type

21.                 // of parameter list – overloaded functions

22.         };

23.          

24.         // implementation part

25.         many_names::many_names(void)    // void

26.         {

27.             length = 8;

28.             width = 8;

29.         }

30.          

31.         many_names::many_names(int len) // one parameter

32.         {

33.         length = len;

34.         width = 8;

35.         }

36.          

37.         many_names::many_names(int len, int wid)   // two parameter

38.         {

39.             length = len;

40.             width = wid;

41.         }

42.          

43.         void many_names::display(void)   // void for display

44.         {

45.             cout<<"From void display function, Area = "<<length * width<<"\n";

46.         }

47.          

48.         void many_names::display(int one)  // 1 parameter

49.         {

50.             cout<<"From int display function, Area = "<<length * width<<"\n";

51.         }

52.          

53.         void many_names::display(int one, int two)  // 2 parameters

54.         {

55.             cout<<"From two int display function, Area = "<<length * width<<"\n";

56.         }

57.          

58.         void many_names::display(float number)  //1 parameter

59.         {

60.             cout<<"From float display function, Area = "<<length * width<<"\n";

61.         }

62.          

63.         // the main program

64.         main()

65.         {

66.             many_names   small, medium(10), large(12,15);

67.             int   gross = 144;

68.             float  pi = 3.1415, payroll = 12.50;

69.           

70.             cout<<"Guess, which function that they invoked???\n";

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

72.             cout<<"-->small.display()\n";

73.             small.display();

74.             cout<<"\n-->small.display(100)\n";

75.             small.display(100);

76.             cout<<"\n-->small.display(gross,100)\n";

77.             small.display(gross,100);

78.             cout<<"\n-->small.display(payroll)\n";

79.             small.display(payroll);

80.             cout<<"\n-->medium.display()\n";

81.             medium.display();

82.             cout<<"\n-->large.display(pi)\n";

83.             large.display(pi);

84.           

85.            // system("pause");

86.         }

 

86 lines: Output:

 

C++ object and class function overloading program examples

 

  • This program illustrates some of the overloaded function names and the rules for their use.  You will recall that the function selected is based on the number and types of the formal parameters only.  The type of the return value is not significant in overload resolution.

  • In this case there are three constructors.  The constructor which is actually called is selected by the number and types of the parameters in the definition.

  • In line 66 of the main program the three objects are declared, each with a different number of parameters and inspection of the results will indicate that the correct constructor was called based on the number of parameters.  The code segment is:

many_names   small, medium(10), large(12, 15);

  • In the case of the other overloaded functions, the number and type of parameters is clearly used to select the proper method.  You will notice that the one function uses a single integer and another uses a single float type variable, but the system is able to select the correct one. (method and function used interchangeably here)

 

13.14   The Default Methods

1.     // program deftmeth.cpp, default method

2.     #include  <iostream>

3.   

4.     #include  <string> // or try #include <cstring>

5.     using namespace std;

6.      

7.     // a class declaration part

8.     class  def

9.     {

10.        int    size;           // a simple stored value

11.        char   *string;    // a name for the stored data

12.        public:

13.             // this overrides the default constructor

14.            def(void);

15.   

16.   // this overrides the default copy constructor

17.    def(def &in_object);

18.   

19.   // this overrides the default assignment operator

20.    def &operator=(def  &in_object);

21.   

22.   //This destructor should be required with dynamic allocation

23.    ~def(void);

24.   

25.   // and finally, a couple of ordinary methods

26.   void  set_data(int  in_size, char  *in_string);

27.   void  get_data(char  *out_string);

28.  };

29.   

30.   // class implementation

31.  def::def(void)

32.  {

33.     size  =  0;

34.     string  =  new  char[2];

35.     strcpy(string, "");

36.  }

37.   

38.  def::def(def  &in_object)

39.  {

40.     size  =  in_object.size;

41.     string  =  new  char[strlen(in_object.string)  +  1];

42.     strcpy(string, in_object.string);

43.  }

44.   

45.  def& def::operator=(def  &in_object)

46.  {

47.    delete [ ]   string;

48.    size = in_object.size;

49.    string = new  char[strlen(in_object.string) + 1];

50.    strcpy(string, in_object.string);

51.    return   *this;    // this pointer

52.  }

53.   

54.  def::~def(void)

55.  {

56.    delete []  string;

57.  }

58.   

59.  void def::set_data(int  in_size,  char  *in_string)

60.  {

61.    size = in_size;

62.    delete  [ ]  string;

63.    string = new   char[strlen(in_string)  +  1];

64.    strcpy(string, in_string);

65.  }

66.   

67.  void def::get_data(char  *out_string)

68.  {

69.     char   temp[10];

70.     strcpy(out_string, string);

71.     strcat(out_string, " = ");

72.     itoa(size, temp, 10);

73.     strcat(out_string, temp);

74.  }

75.   

76.  // the main program

77.  void  main()

78.  {

79.         char  buffer[80];

80.         def  my_data;

81.         my_data.set_data(8, " small size, override default constructor ");

82.         my_data.get_data(buffer);

83.         cout<<" content of buffer!!\n"<<buffer<<"\n";

84.        

85.        def   more_data(my_data);

86.        more_data.set_data(12, " medium size, override copy constructor");

87.        my_data.get_data(buffer);

88.        cout<<"\n content of buffer 2nd round!!\n"<<buffer<<"\n";

89.      

90.      

91.       my_data = more_data;

92.       my_data.get_data(buffer);

93.       cout<<"\n content of buffer 3rd round, assignment

94.                                           overload!!\n"<<buffer<<"\n";

95.      

96.       // system("pause");

97.  }

 

97 lines: Output:

 

C++ object and class default, copy method program examples

  1. If no constructors are defined by the writer of a class, the compiler will automatically generate a default constructor and a copy constructor.  Both of these constructors will be defined for you later.

  2. If the class author includes any constructor in the class, the default constructor will not be supplied by the constructor.

  3. If the class author does not include a copy constructor, the compiler will generate one, but if the writer includes a copy constructor, the compiler will not generate one automatically.

  4. If the class author includes an assignment operator, the compiler will not include one automatically; otherwise it will generate a default assignment operator.

def(void);

my_data.set_data(8, " small size, override default constructor ");

 

13.15    The Copy Constructor

  // this overrides the default copy constructor

def(def &in_object);

...

def::def(def  &in_object)

{

   size  =  in_object.size;

   string  =  new  char[strlen(in_object.string)  +  1];

   strcpy(string, in_object.string)

}

...

def::~def(void)

{

  delete [ ] string;

}

...

more_data.set_data(12, " medium size, override copy constructor");

13.16    The Assignment,  (=) Operator

  // this overrides the default assignment operator

def &operator=(def  &in_object);

...

def& def::operator=(def &in_object)

{

  delete [ ]   string;

  size = in_object.size;

  string = new char[strlen(in_object.string) + 1];

  strcpy(string, in_object.string);

  return   *this;

}

...

my_data = more_data;

tenouk C++ encapsulation code samples

 

 

 

 

 

 

 

 

 

 

 

 

Further related C++ reading:

 

  1. The source code for this tutorial is available in C++ Data Encapsulation source codes.
  2. Check the best selling C / C++ and object oriented books at Amazon.com.
  3. MFC library class hierarchy chart.

 

 

 

 

 

 

|< C++ Data Encapsulation 5 | Main | C++ Data Encapsulation 7 >| Site Index | Download |


C++ Class and Object - The Encapsulation and Data Abstraction:  Part 1 | Part 2 | Part 3 | Part 4