Results 1 to 3 of 3

Thread: Classes – Access Control, Constructors and Overloads

  1. #1
    Junior Member
    Join Date
    Dec 2004
    Posts
    28

    Classes – Access Control, Constructors and Overloads

    Note: Again we use php braces only to preserve syntax.

    Classes – Access Control, Constructors and Overloads

    Public Private and Protected members

    Classes allow us to group data with the methods that operate on the data. This allows us to define new data types and to create instances or objects of this newly defined data type. It is both common and default for class data to be private, this supports encapsulation. We define class methods to act as an interface between the users and the class. Class methods have access to the private data of the class to which they belong. It is said that members of a class are private unless stated otherwise. Access modifiers are the keywords public, private and protected are used to change this default behavior. Sometimes it is desirable to make member data public and a class method private. To do so we use the keywords as shown below.

    PHP Code:
    enum COLOR{BLACKWHITEREDGREENBLUE};
    enum BOOL{FALSETRUE};

    class 
    Window
    {
        public:
            
    void Draw();
            
            
    int GetWidth();
            
    int GetHeight();
            
    void SetWidth(int);
            
    void SetHeight(int);
            
            
    COLOR mColor;
                    
        private:
            
    BOOL InternalPaint();
            
            
    int width;
            
    int height;
    }; 
    We see here that mColor is public rather then private because we defined it in the public section of our class. This means that we can access this data directly, say we have a Window object myWindow we can access mColor via myWindow.mColor and there is no problem. Most of our methods are public except for one, InternalPaint is under the private section thus we cannot write myWindow.InternalPaint() because of its private nature. InternalPaint might be called by Draw() however which is public. Remember all methods can access private data, InternalPaint included. Just the same all methods of a class can access private methods. Thus we could say myWindow.Draw() and then Draw() itself might then call InternalPaint(). The protected keyword is very similar to private, in fact we wont really notice any difference until we discuss Inheritance. As was true with private data is true for protected data. We cannot access protected data directly, only via interface methods. All methods weather they be public, private or protected can always access private and protected members of the class in which they belong.

    Constructors and Deconstructors

    All classes have a Constructor and Deconstructor, these are methods who's purpose is to take care of initializing the class, allocating and deallocating memory and are called when an object is created and destroyed. A default constructor and deconstructor is provided by the compiler if you forget or neglect to define any. These special methods have the same name as the class itself, for our window class these would be Window() and ~Window(). As you might guess Window() is the constructor and ~Window() is the deconstrutor. Constructors cannot return anything not even void, the same goes for the deconstrutor. They can however take any number of arguments. They both must be public. As stated the purpose of the constructor is to initialize the class, allocate memory if necessary, and to setup the object. Lets look at an example.

    PHP Code:
    enum COLOR{BLACKWHITEREDGREENBLUE};
    enum BOOL{FALSETRUE};

    typedef int PIXELS;

    class 
    Window
    {
        public:
            
    Window(PIXELS widthPIXELS height);
            ~
    Window();
                    
        private:
            
    PIXELS mWidthmHeight;
    };

    Window::Window(PIXELS widthPIXELS height)
    {
        
    mWidth width;
        
    mHeight height;
    }

    Window::~Window()
    {
    }

    int main(int argcchar *argv[])
    {
        
    Window myWnd(67);
        
        return 
    1;

    It is a tradition of some programmers to prefix member data names with m, hence mWidth, this is not necessary. Here we defined our own constructor and deconstrutor. Our constructor takes two PIXELS which were typedefed as ints earlier. It makes use of these arguments by assigning them to the private data mWidth and mHeight. Because we did not allocate any memory our deconstrutor does not need to do anything. However when it comes time to create our myWnd object we must now supply two ints as arguments since thats what the constructor asks for. There is however a shortcut way to initialize data members via the constructor. Examine the following syntax carefully.

    PHP Code:
    Window::Window(PIXELS widthPIXELS height): mWidth(width), mHeight(height)
    {

    Here we see a nifty shortcut to initializing members. The result is the same however it saves space for other stuff like allocating memory if you want. It is in fact very common to initialize members this way. This is all great however we have a slight problem, and that is every time we want to create a Window object we must pass 2 arguments. It is no longer possible to declare a window object by Window myWnd; and this can be rather unpleasant. Suppose you wanted to set a default value for mWidth and mHeight so that if no arguments are passed then the defaults would be assigned. Indeed this is possible two ways. One is by using default parameters. Consider the following.

    PHP Code:
    enum COLOR{BLACKWHITEREDGREENBLUE};
    enum BOOL{FALSETRUE};

    typedef int PIXELS;

    class 
    Window
    {
        public:
            
    Window(PIXELS width 1024PIXELS height 768);
            ~
    Window();
                    
        private:
            
    PIXELS mWidthmHeight;
    };

    Window::Window(PIXELS widthPIXELS height): mWidth(width), mHeight(height)
    {
    }

    Window::~Window()
    {
    }

    int main(int argcchar *argv[])
    {
        
    Window myWnd1(800600);
        
    Window myWnd2;  // Defaults to 1024 x 768
        
        
    return 1;

    Here we took advantage of default parameters, on line 9 we said to the compiler if no arguments are supplied then use the default values of 1024 and 768. If arguments are supplied then ignore the defaults and use what we were given. On line 26 and 27 we see two Window objects are created, one with user supplied data, the other taking advantage of our default values. We could have also said Window myWnd2(800); and this would also be valid, since both parameters are defaulted in our constructor, we are saying use 800 for the first parameter but for the remainder parameters use the defaults. There is one quirk and that is when a parameter is set to have a default value, all remaining parameters if any to the right must also be defaulted. This means we cannot declare a constructor with Window(PIXELS width = 1024, PIXELS height); because the first parameter has a default value but the parameter to the right does not. We could however write Window(PIXELS width, PIXELS height = 768); and this would be perfectly valid.

    Overloading Functions and Methods

    It is possible to have two or more class methods with the same name if each has a unique signature. The same is true with global functions. It is quite common to overload the constructor, it might be desirable to declare a constructor that takes no arguments, along side a constructor that takes arguments. Here we illustrate this idea.

    PHP Code:
    enum COLOR{BLACKWHITEREDGREENBLUE};
    enum BOOL{FALSETRUE};

    typedef int PIXELS;

    class 
    Window
    {
        public:
            
    Window(): mWidth(1024), mHeight(768) {}
            
    Window(PIXELS widthPIXELS height): mWidth(width), mHeight(height) {}
            ~
    Window() {}
                    
        private:
            
    PIXELS mWidthmHeight;
    };

    int main(int argcchar *argv[])
    {
        
    Window myWnd1(800600);
        
    Window myWnd2;
        
        return 
    1;

    Here we illustrate two new concepts, overloaded constructors and inline methods. We have overloaded our constructor in such a way that if no arguments are passed when creating our object, we get default values, but we are still free to pass both arguments to define our own window. The compiler is smart enough to determine which one to call based on what if any arguments you pass. That same is true with global functions, the compiler makes the decision which one to call based on the arguments list. Secondly we just introduced the concept of inline methods. We relocated the definition of our constructor to inside the class. This makes the constructor inline, this changes things. By making a method inline we are telling the compiler to not give the method its own code space but rather to search and replace all parts of the code where the method is called. This almost sounds like macros which I despise but has the advantage of speeding up the program and the disadvantage of making the file size bigger. The constructor and deconstructor are both simple enough to be included directly in the class declaration. Sometimes however you wish to make a method inline but it is too long to fit neatly inside the class. In these cases we can still make the method inline by using the keyword inline outside of the class. The following illustrates this idea.

    PHP Code:
    enum COLOR{BLACKWHITEREDGREENBLUE};
    enum BOOL{FALSETRUE};

    typedef int PIXELS;

    class 
    Window
    {
        public:
            
    Window();
            
    Window(PIXELS widthPIXELS height);
            ~
    Window() {}  // inline within class
                    
        
    private:
            
    int mArea;
            
    PIXELS mWidthmHeight;
    };

    inline Window::Window(): mWidth(1024), mHeight(768), mArea(1024*768)
    {
        
    // Do som stuff here...
        // That would make putting this definition inside the class ugly
        // ...
    }

    inline Window::Window(PIXELS widthPIXELS height): mWidth(width), mHeight(height)
    {
        
    mArea mWidth mHeight;
    }

    int main(int argcchar *argv[])
    {
        
    Window myWnd1(800600);
        
    Window myWnd2;
        
        return 
    1;

    Here we have a new member mArea that stores the area of the window, since getting the value for mArea requires simple math we decide that this might make our class ugly to jam the definition inside so we move our definitions back outside this time with the keyword inline. Our constructors are still inline so we gain the speed benefit, and we have more room to do our math. The destructor is also inline but we left the definition inside the class since it is so small. This also supports the encapsulation idea since we the user of the class have no way to set the value of mArea. We cannot set private data without accessor methods. The constructor methods hide the details of what is going on. If it don't need to be public then it should be private.

    Conclusion

    We learned that classes are private by default and we can use the keywords public, private and protected to change this default behavior. We also learned that constructors are useful for setting up objects such as initialiseing member data. If we don't supply our own constructor and deconstructor, the compiler will make one for us. We discussed function and method overloading and how constructors are often overloaded. The use of inline functions can make programs faster since the inline method is not put into a code space of its own but is rather copy and pasted where it is needed. There was a disadvantage to using inline methods since our executable output file will be larger in size.

  2. #2
    ********** |ceWriterguy
    Join Date
    Aug 2004
    Posts
    1,608
    Up for some constructive criticism? You'll get more folks to view your stuff if you go ahead and post it in here instead of attaching them... As a newbie with 9 whole posts under you, we don't know you from Adam - you could be trying to load us up with malware or something ...
    Even a broken watch is correct twice a day.

    Which coder said that nobody could outcode Microsoft in their own OS? Write a bit and make a fortune!

  3. #3
    Junior Member
    Join Date
    Dec 2004
    Posts
    28
    Thanks, I will convert them later tonight and post. I apreciate it.

    I had an acount journy101 which i have forgotten the password for so I created this acount. Periodicaly i change my passwords and must have forgoten to change it on antionline. Someday I will remember

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •