|< C++ Encapsulation 2 | Main | C++ Encapsulation 4 >| Site Index | Download |


 

 

 

 

MODULE 12b

 MORE ON ENCAPSULATION CODE EXAMPLES 3

 

 

 

 

 

My Training Period: xx hours

 

This is a continuation from the previous Module.  When you copy and paste to the text or compiler editor, make it in one line!  This Module is a transition from C to C++ and Topics of C++ such as Functions, Arrays, Pointers and Structure that have been discussed in C will not be repeated.  The source code is available in C++ Encapsulation source code.

 

The C++ programming skills that should be acquired is: To understand and use the object packaging.

 

 

 

 

12.10    Data Hiding

  • The three programs examples we have just studied illustrate a concept of data hiding.

  • Since the only information the user of the class really need is the class header, the details of the implementation can be kept hidden from him.

  • Since he doesn’t know exactly what the implementer did, he must follow only the definition given in the header file.  As mentioned earlier, accidental corruption of data is also prevented.

  • Another reason for hiding the implementation is economic.  The company that supplied you with your C++ compiler gave you many library functions but did not supply the source code of the library functions, only the interface to each function.

  • You know how to use the functions but you do not have the details of implementation, nor do you need them.  Likewise, a class library vendors can develop, which supplies users with libraries of high quality, completely developed, and tested classes, for a licensing fee.

  • Since the user only needs the interface defined, he can be supplied with the interface and the object (compiled) code for the class and can use it in any way he desired.  The vendors’ source code is protected from accidental or intentional compromise and he can maintain complete control over it.

  • But keep in mind that may be this is not the case for the open source community :o).

12.11    Abstract Data Type

  • An abstract data type is a group of data, each of which can store a range of data values and a set of methods or functions that operate on that data.  Since the data are protected from any outside influence, it is protected and said to be encapsulated.

  • Also, since the data is somehow related, it is a very coherent group of data that may be highly interactive with each other, but with little interaction outside the scope of its class.

  • The methods, on the other hand, are coupled to the outside world through the interface, but there are a limited number of contacts with or a weak coupling with the outside.

  • Because of the tight coherency and the loose coupling, ease of maintenance of the software should be greatly enhanced.

  • The variables could have been hidden completely out of sight in another file, but because the designers of C++ wished to make the execution of the completed application as efficient as possible, the variables were left in the class definition where they can be seen but not used.

12.12  The union in C++

  • In C++ union can contain access specifiers (public, protected, private), member data, and member functions, including constructors and destructors.

  • It cannot contain virtual functions or static data members. It cannot be used as a base class, nor can it have base classes. Default access of members in a union is public.  In C++, the union keyword is unnecessary.

  • Same as in C, a union type variable can hold one value of any type declared in the union by using the member-selection operator (.) to access a member of a union.

  • You can declare and initialize a union in the same statement by using enclosed curly braces. The expression is evaluated and assigned to the first field of the union.

  • A program example:

#include <iostream>

using namespace std;

 

union Num

{

   int      ValueI;

   float    ValueF;

   double   ValueD;

   char    ValueC;

};

 

void main()

{

    // optional union keyword, ValueI = 100

    Num TestVal = {100};

 

    cout<<"\nInteger = "<<TestVal.ValueI<<endl;

    TestVal.ValueF = 2.123L;

    cout<<"Float = "<<TestVal.ValueF<<endl;

    cout<<"Uninitialized double = "<<TestVal.ValueD<<endl;

    cout<<"Some rubbish???"<<endl;

    TestVal.ValueC = 'U';

    cout<<"Character = "<<TestVal.ValueC<<endl;

}

 

Output:

 

C++ object oriented union example

 

12.13    The  struct  in  C++

#include <iostream>

using namespace std;

 

struct Num

{

   int      ValueI;

   float    ValueF;

   double   ValueD;

   char    ValueC;

};

 

void main()

{

    struct Num TestVal = {100};

 

    cout<<"\nInteger = "<<TestVal.ValueI<<endl;

    TestVal.ValueF = 2.123L;

    cout<<"Float = "<<TestVal.ValueF<<endl;

    cout<<"Uninitialized double = "<<TestVal.ValueD<<endl;

    cout<<"Better than union"<<endl;

    TestVal.ValueC = 'U';

    cout<<"Character = "<<TestVal.ValueC<<endl;

}

 

Output:

 

C++ object oriented struct

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Program Examples and Experiments

 

 

Example#1

// creating simple class, STEP #1

#include  <iostream>

using namespace std;

 

// class, declaration part

class line

{

     public:

     line(void);

     ~line(void);

};

 

// class implementation part

line::line(void)

{ }

 

line::~line(void)

{ }

 

// main program

int main()

{

    line   LineOne;

 

    cout<<"Just program skeleton\n";

    return 0;

}

 

Output:

 

C++ object oriented class program example

// creating simple class, STEP #2

#include  <iostream>

using namespace std;

 

// class, declaration part

class line

{

   char*  color;

   int  pattern;

   public:

       line(void);

       char*   LineColor(char*){ return  color = "GREEN";};

       int    LinePattern(int pattern){return pattern;};

       ~line(void);

};

 

// class implementation part

line::line(void)

{

   // constructors value…

   pattern = 12;

}

 

line::~line(void)

{

   color = NULL;

   pattern = 0;

}

 

// main program

void main()

{

      line   LineOne;

      int x = 10;

     

    cout<<"Simple Line attribute class\n";

    cout<<"Using some user supplied value\n";

       cout<<"------------------------------"<<"\n";

       cout<<"Line's Color        ----> "<<LineOne.LineColor("")<<"\n";

       cout<<"Line's pattern type ----> "<<LineOne.LinePattern(x)<<"\n";

}

 

Output:

 

C++ object oriented class program example

int    LinePattern(int pattern){return pattern;};

int    LinePattern(int){return pattern;};

C++ object oriented class program example

int    LinePattern(int pattern){return pattern;};

int    LinePattern(int){return pattern = 13;};

pattern = 12;

C++ object oriented class program example

// creating simple class, STEP #3, complete

#include  <iostream>

using namespace std;

 

// class, declaration part

class line

{

       char*  color;

       float  weight;

       float  length;

       char * arrow;

 

       public:

           line(void);

           char* LineColor(char* color){return color;};

           float LineWeight(float weight){return weight;};

           float LineLength(float length){return length;};

           char *LineArrow(char* arrow){return arrow = "YES";};

           ~line(void);

};

 

// implementation part

line::line(void)

{

       //constructors or initial values…

       weight = 0.25;

       length = 10;

}

 

line::~line(void)

{

       color = NULL;

       weight = 0;

       length = 0;

       arrow = NULL;

}

 

/ main program

void main()

{

       line   LineOne;

 

       float x = 1.25, y = 2.25;

       char newcolor[10] = "BLUE", *colorptr;

 

       cout<<"Line attributes, very simple\n";

       cout<<"     class example\n";

       cout<<"----------------------------"<<"\n";

 

       colorptr = newcolor;

       // just for testing the new attribute values...

       cout<<"\nAs normal variables....."<<endl;

       cout<<"Test the new line weight = "<<x<<endl;

       cout<<"Test the new line length = "<<y<<endl;

       cout<<"Test the new line color is = "<<colorptr<<endl;

 

       cout<<"\nUsing class......."<<endl;

       cout<<"New line's color  ----> "<<LineOne.LineColor(colorptr)<<"\n";

       cout<<"New line's weight ----> "<<LineOne.LineWeight(x)<<" unit"<<"\n";

       cout<<"New line's length ----> "<<LineOne.LineLength(y)<<" unit""\n";

 

       cout<<"Line's arrow      ----> "<<LineOne.LineArrow(" ")<<"\n\n";

}

 

Output:

 

C++ object oriented class program example

// testing the constructor and destructor

#include <iostream>

using namespace std;

 

// class declaration part

class TestConsDest

{

       // member variable...

       public:

       int TestVar;

 

       // member functions, constructor and destructor...

       public:

       TestConsDest();

       int DisplayValue();

       ~TestConsDest();

};

 

// class implementation part

// constructor...

TestConsDest::TestConsDest()

{

       // test how the constructor was invoked...

       // static-retain the previous value…

       static int x=1;

       cout<<"In Constructor, pass #"<<x<<endl;

       x++;

}

 

// a simple function returning a value...

int TestConsDest::DisplayValue()

{

       return TestVar = 100;

}

 

// destructor...

TestConsDest::~TestConsDest()

{

       // test how destructor was invoked...

       static int y=1;

       cout<<"In Destructor, pass #"<<y<<endl;

       y++;

       // explicitly...

       TestVar = 0;

}

 

// main program

int main()

{

       // instantiate two objects...

       // constructor should be invoked...

       // with proper memory allocation...

       TestConsDest Obj1, Obj2;

 

       cout<<"Reconfirm the allocation for Obj2 = "<<&Obj2<<endl;

       cout<<"Default constructor value assigned = "<<Obj1.DisplayValue()<<endl;

       cout<<"In main(), testing..."<<endl;

       cout<<"What about Obj1 allocation? = "<<&Obj1<<endl;

       cout<<"Default constructor value assigned = "<<Obj1.DisplayValue()<<endl;

       return 0;

}

 

Output:

 

 

 

 

 

 

 

 

 

 

 

 

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

 

C++ object oriented class constructor and destructor

 

 

C++ object oriented class constructor and destructor

Final remarks: Think simple!!!

 

// a class skeleton program

#include <iostream>

using namespace std;

 

// the base class declaration

class BaseClass

{

//  member variables declaration

// declare all your variables here

// with optional access restrictions

public:

       int p;

 

// this keyword will be explained later...

protected:

       float q;

 

private:

       char r;

 

// member functions or methods

// define your functions here also with optional access restrictions

public:

       // constructor

       BaseClass();

       // destructor

       ~BaseClass();

 

private:

       int Funct1();

 

protected:

       void Funct2();

};

 

// class implementation part

// define your method here

BaseClass::BaseClass()

{ }

 

int BaseClass::Funct1()

{return 0;}

 

// constructor implementation

void BaseClass::Funct2()

{}

 

// destructor implementation

BaseClass::~BaseClass()

{}

 

// the main program, start instantiate objects here...

int main(void)

{

       cout<<"------class test message----"<<endl;

       cout<<"This just a class skeleton..."<<endl;

       cout<<"It just simple, think simple!"<<endl;

 

       return 0;

}

 

Output:

 

C++ object oriented class program example

// program class.cpp using class instead of struct

#include <iostream>

using namespace std;

 

// class declaration part

class item

{

     // private by default, it is public in struct

     int  keep_data;

     // public part

     public:

        void  set(int enter_value);

        int  get_value(void);

};

 

// class implementation part

void item::set(int enter_value)

{

      keep_data = enter_value;

}

 

int item::get_value(void)

{

      return  keep_data;

}

 

// main program

void main()

{

    // three objects instantiated of type item class

     item    John_cat, Joe_cat, Big_cat; 

    // a normal variable

     int   garfield;

 

     // assigning values

     John_cat.set(111);

     Joe_cat.set(222);

     Big_cat.set(333);

     garfield = 444;

    // John_cat.keep_data = 100;   

    // Joe_cat.keep_data = 110;    

    // these are illegal because keep_data now, is private by default

 

    cout<<"Accessing data using class\n";

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

    cout<<"Data value for John_cat is "<<John_cat.get_value()<<"\n";

    cout<<"Data value for Joe_cat is "<<Joe_cat.get_value()<<"\n";

    cout<<"Data value for Big_cat is "<<Big_cat.get_value()<<"\n";

    cout<<"\nAccessing data normally\n";

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

    cout<<"Data value for garfield is "<<garfield<<"\n";

}

 

Output:

 

C++ object oriented class program example

///////// -simpleclass.cpp- ////////

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

///// creating a simple class/////

#include <iostream>

using namespace std;

 

// class, declaration part

class line

{

        char*  color;

        float  weight;

        float  length;

        char * arrow;

 

        public:

            line(void);

            char*    LineColor(char* color){return color;};

            float    LineWeight(float weight){return weight;};

            float    LineLength(float length){return length;};

            char    *LineArrow(char* arrow){return arrow = "YES";};

            ~line(void);

};

 

// implementation part

line::line(void)

{

        // constructors or default initial values.

        weight = 0.25;

        length = 10;

}

 

line::~line(void)

{

        color = NULL;

        weight = 0;

        length = 0;

        arrow = NULL;

}

 

// main program

int main()

{

        line   LineOne;

 

        float x = 1.25, y = 2.25;

        char newcolor[10] = "BLUE", *colorptr;

 

        cout<<"Line attributes, very simple\n";

        cout<<"     class example\n";

        cout<<"----------------------------"<<"\n";

 

        colorptr = newcolor;

        // just for testing the new attribute values...

        cout<<"\nAs normal variables....."<<endl;

        cout<<"Test the new line weight = "<<x<<endl;

        cout<<"Test the new line length = "<<y<<endl;

        cout<<"Test the new line color is = "<<colorptr<<endl;

 

        cout<<"\nUsing class......."<<endl;

        cout<<"New line's color  ----> "<<LineOne.LineColor(colorptr)<<"\n";

        cout<<"New line's weight ----> "<<LineOne.LineWeight(x)<<" unit"<<"\n";

        cout<<"New line's length ----> "<<LineOne.LineLength(y)<<" unit""\n";

        cout<<"Line's arrow      ----> "<<LineOne.LineArrow(" ")<<"\n\n";

        return 0;

}

 

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

[bodo@bakawali ~]$ ./simpleclass

 

Line attributes, very simple

     class example

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

 

As normal variables.....

Test the new line weight = 1.25

Test the new line length = 2.25

Test the new line color is = BLUE

 

Using class.......

New line's color  ----> BLUE

New line's weight ----> 1.25 unit

New line's length ----> 2.25 unit

Line's arrow      ----> YES

 

Tenouk C++ encapsulation code samples

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Further C++ class related reading:

 

  1. MFC library class hierarchy chart.
  2. The source code is available in C++ Encapsulation source code.
  3. Check the best selling C / C++ books at Amazon.com.
  4. C++ standards reference: ISO/IEC 14882:1998 on the programming language C++.

 

 

 

 

 

|< C++ Encapsulation 2 | Main | C++ Encapsulation 4 >| Site Index | Download |


C++ Object, Class and Encapsulation:  Part 1 | Part 2 | Part 3