C++ Information Hiding, Abstraction, Access Specifiers

This is a discussion on C++ Information Hiding, Abstraction, Access Specifiers within the C++ Programming forums, part of the General Programming Boards category; Hey guys, I'm a beginner at C++ programming and can't seem to progress past classes and objects. I get the ...

  1. #1
    The Dragon Reborn
    Join Date
    Nov 2009
    Location
    Dublin, Ireland
    Posts
    629

    C++ Information Hiding, Abstraction, Access Specifiers

    Hey guys,
    I'm a beginner at C++ programming and can't seem to progress past classes and objects.
    I get the concept about classes.
    It is a blue print or design for something. But we can't use classes as we can;'t use a design for a car..we have to breathe life into it so therefore we instantiate a class to create an object.
    Encapsulation, I understand is grouping data members and functions in a class.
    But, what I don't understand is the use of access modifiers or in fact information hiding. What does it mean to hide information?

    I can have 100m lines of code and I give it to a "user" which I understand as another programmer and not end user. the user can still see the code or blueprint of the class so we are not really hiding anything are we, the other programming has eyes!?
    Or maybe that other classes or functions can't see the data members, which doesn't make sense to me. The compiler or class isn't going to say "hey there! class Animal has data member height of a value of 5! let me change it to 19 instead! Lol it doesn't make sense to me - another class or a compiler isn't bloody Skynet! haha
    for example i have a class.
    Code:
      class Animal
      {
           public:
            void setTypeOfAnimal() ;
            void getTypeOfAnimal() ;
    
           private:
             int height, weight;
             string type;
             
      }
    when I instantiate the class,
    Code:
    Animal Dog; Dog.height = 100 ;
    i have to use a function to do it for me!
    Code:
    Dog.setTypeOfAnimal()
    What is the point? it is essentially the same result at then end.
    Can anyone please explain all this for me and with practical examples in your work why you think it is important to hide info or what hiding data means. and also with practical code. And when you write the code can you please make it well indented. I haven't done any C++ coding with classes - just learning the theory - so it will put me off.
    If you want to give me a definition, please don't I can read the damn book which is useless to me.

    Also what IS abstraction. It sounds to me like encapsulation or "data hiding".
    Please help me!
    Eman

  2. #2
    Registered User whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    7,525
    I'm a beginner at C++ programming and can't seem to progress past classes and objects.
    Relax bro, it's a complicated subject, and C++ makes it a pretty big deal, whether you'll eventually come to like C++'s OO design or not.

    What does it mean to hide information?

    I can have 100m lines of code and I give it to a "user" which I understand as another programmer and not end user. the user can still see the code or blueprint of the class so we are not really hiding anything are we, the other programming has eyes!?
    That's not really the point.

    And of course, any class that you write personally you are going to be familiar with the data and methods of the class.

    The same cannot be said of other people, especially if you distribute a compiled library, and use the pimpl idiom in the header file(s). It's not really that we want to hide what a class is, but even if only out of legal interests, you could well mean to hide the implementation details.

    Also what IS abstraction. It sounds to me like encapsulation or "data hiding".
    It is that, but there are other concerns. A layer of abstraction often makes code more portable from system to system, since they are pretty unique. There are detailed descriptions on the web you could find but honestly I think those are the three reasons to use abstraction. Where portability is concerned all you have to do to port is implement a common interface, which alone involves rewriting classes or functions with system specific code. All that to make what we have already work on something else.

    It all looks rather stupid now, but you are doing contrived work to get the hang of things. Pretty much anything realistic would help make things concrete for you. Have you ever thought about the object oriented work the programs you use everyday must do? And there are reasons that those things follow the implementation guidelines you are learning now. The code has to be manageable, for one, and for two, you wouldn't want some of the information you give programs to be freely available, and thus corruptible.
    Last edited by whiteflags; 09-25-2010 at 03:01 AM.

  3. #3
    C++まいる!Cをこわせ! Elysia's Avatar
    Join Date
    Oct 2007
    Posts
    22,169
    The point of abstraction is to protect your code from changes. Sure you can manipulate your class directly, but if you change how that class handles things, the code will break.
    Now, imagine, say, a register. At first, it might use a vector to hold the information. Now, imagine a huge project built around that register. We insert, delete, search, modify stuff. Now, imagine that application doing these operations on the class in a huge number of places. That is, modifying the vector directly.
    Now, imagine we want to change that vector to a linked list. OK. Fine. But oh no. This will break code in a huge amount of places, which we have to go back to fix.
    On the other hand, if we used set/get/search/etc, and not modify the class directly, those places would call these functions. Now, if we change the vector to a list, we only have to modify those functions and the rest of the code works fine.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.
    For information on how to enable C++11 on your compiler, look here.
    よく聞くがいい!私は天才だからね! ^_^

  4. #4
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    20,968
    Quote Originally Posted by Elysia
    The point of abstraction is to protect your code from changes.
    I would consider that the point of encapsulation, not abstraction.
    C + C++ Compiler: MinGW port of GCC
    Version Control System: Bazaar

    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  5. #5
    C++まいる!Cをこわせ! Elysia's Avatar
    Join Date
    Oct 2007
    Posts
    22,169
    OK, well maybe the lines blur between those two. Just consider encapsulation and abstraction as a way to protect the code from changes and make it flexible.
    (They use the word differently than I. Grrr!)
    More can be found on Wikipedia:
    Abstraction (computer science) - Wikipedia, the free encyclopedia
    Encapsulation (object-oriented programming) - Wikipedia, the free encyclopedia
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.
    For information on how to enable C++11 on your compiler, look here.
    よく聞くがいい!私は天才だからね! ^_^

  6. #6
    Registered User whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    7,525
    (They use the word differently than I. Grrr!)
    Laserlight and I actually don't. I've been trying to think of a way to reply to you, since you also seem innocently confused. I can only think... you say abstraction protects code from changes, but also admit abstraction is nice when you want to make changes to something specific, without breaking an interface.

    The encapsulation part deserves credit for making things easy to change and establishing implementation. The abstraction part is due credit for making things easy to use, port, and understand.

  7. #7
    C++まいる!Cをこわせ! Elysia's Avatar
    Join Date
    Oct 2007
    Posts
    22,169
    Quote Originally Posted by whiteflags View Post
    Laserlight and I actually don't. I've been trying to think of a way to reply to you, since you also seem innocently confused.
    Obviously. The terminology I use apparently appears to be wrong.
    But it is no matter. We learn as we go.
    Wikipedia explains it all.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.
    For information on how to enable C++11 on your compiler, look here.
    よく聞くがいい!私は天才だからね! ^_^

  8. #8
    The Dragon Reborn
    Join Date
    Nov 2009
    Location
    Dublin, Ireland
    Posts
    629
    I'm sorry but I still don't get it?
    What is the "interface". I haven't done anything like Linkedlist can you make it simpler please.
    "The point of abstraction is to protect your code from changes"
    What changes? Changes from another programming? Could anyone please explain with a simple code? or real life example?
    and thanks for the quick reply. Didn't expect any.

  9. #9
    Registered User
    Join Date
    Aug 2010
    Location
    Poland
    Posts
    671
    Quote Originally Posted by Eman View Post
    I'm sorry but I still don't get it?
    What is the "interface". I haven't done anything like Linkedlist can you make it simpler please.
    "The point of abstraction is to protect your code from changes"
    What changes? Changes from another programming? Could anyone please explain with a simple code? or real life example?
    and thanks for the quick reply. Didn't expect any.
    Very shortly (sorry if I'm explaining it in a bad way):

    Interface is something that allows communication between two devices/objects. Interface may refer to an application programming interface as well as to a specific kind of object (google 'IUnknown'). In the first case, 'interface' describes a collection of classes or functions (or anything else) that allows to write programs under specific environment.

    Let's say, you need a software controlling some device, let's say it's a mouse. You want this software to work with different kinds of mice. Of course, all of the mice can click with 2/3 buttons and scroll with the middle one. This is their only common feature. Some mice are optical, some are not.

    Your code to control the mouse can be quite compilcated, taking into consideration many factors (like the time between two clicks, speed of moving, set-up for left-handed or right-handed).

    The most basic thing you need is scanning the mouse movement. To do this, you would probably acquire light diode status (in the case of an optical mouse) and status of rollers (in the case of a mechanical one).

    Because you check the mouse status in many places of your software, it would be a very bad idea to check what kind of mouse is currently plugged in. Here comes in the interfaces.

    Code:
    class MouseListener {
    public:
        virtual int GetVerticalShift();
        virtual int GetHorizontalShift();
        virtual int GetScrollerShift();
        virtual bool IsLeftDown();
        virtual bool IsRightDown();
        virtual bool IsMiddleDown();
    };
    As you can see, with these 6 methods given you do not care what kind of mouse you have currently plugged in, because it's an encapsulated feature. All of the technical principles are hidden in this class (checking what kind of mouse is plugged in, etc).
    MouseListener provides you the most basic operations for every kind of mouse - if the mouse does not have a scroller, the GetScrollerShift would always return 0.

    We could go even farther. We could create a class:

    Code:
    // any pointing device (mouse, touchpad)
    class PointingDeviceListener {
    public:
        virtual int GetVerticalShift();
        virtual int GetHorizontalShift();
    };
    
    // simple two-button mouse
    class Mouse2Listener : public PointingDeviceListener {
    public:
        virtual bool IsLeftDown();
        virtual bool IsRightDown();
    };
    
    // three-button mouse with scroller
    class Mouse3Listener : public MouseListener {
    public:
        virtual bool IsMiddleDown();
        virtual int GetScrollerStatus();
    };


    MouseListener is something that you use in every point of your program. If the implementation of the MouseListener changes, your program will not be affected.
    And if you want to use this code for touchpad, just plug in the touchpad and the code will work.

    And there is much more to say.
    Last edited by kmdv; 09-25-2010 at 06:59 AM.

  10. #10
    Registered User
    Join Date
    Jan 2009
    Location
    Sweden
    Posts
    8
    I will make a try to explain.

    You have a register class someone made and you need this register class in a software youīre making. This register class has methods to add, edit and delete from the register.

    Because someone else made this register class and gave you the interface to work with the register. You donīt need to know how itīs done. You just have to know how to tell the register object to do what you want it to do. So you can focus on your part of the software and donīt have to care about how the register class works. (Abstraction)

    Lets say that the person who made the register class found a way to optimize the class. This require some changes in the class code. But you donīt have to worry because the interface that youīre using wont change. Only whatīs happening under the surface.


    class methods (et/edit/add/delete/etc)
    --------------------------
    Code for set/edit/add/delete/etc to make them do something.


    So if ------- is the surface. You only know about set/edit etc. But under the surface someone has made all the functionality for these operations that you donīt have you worry about. You just need to know how to "talk" to them.

    So you create a register object. Tell it to add a entry and donīt have to care about how it adds a entry. Thatīs the problem for the creator of the register class to figure out.




    If someone find that Im explaining something wrong. Please tell me. I had the same question myself a few years ago and this is somewhat how I came to understand how it works.
    Last edited by Baafen; 09-25-2010 at 06:57 AM.

  11. #11
    The Dragon Reborn
    Join Date
    Nov 2009
    Location
    Dublin, Ireland
    Posts
    629
    Very good guys. I think I'm actually coming to an understanding of "information hiding".
    So someone designs a class and I can use it without needing to understand how it works or validates data. And concentrate on my own code instead.

    I wouldn't know but what if for example one of the methods
    IsLeftDown - if I wanted to use it wouldn't I need to know the number of parameters the function can take? So I would still have to know a little bit of what the class does as another programmer,how many parameters what type of argument and stuff -right?.

    Can some please explain to me the point of access modifiers/specifiers?
    what is the point of making a data member private?
    for example i have 2 functions isPrime() and isLoop() or whatever. The variables are local to the functions. Each function cannot see the other functions so I guess they can be referred to as private. But even lets say the functions in isPrime() were public/global, isLoop() and main() can now see them I still wouldn't expect the isPrime() or main() to grow a brain and say let me mess with the data members in isPrime() cause i can see it.
    or why can't I just do
    [code]
    class Animal
    {
    public:
    void setTypeOfAnimal() ;
    void getTypeOfAnimal() ;

    private:
    int height, weight;
    string type;

    }
    int main()
    {
    Animal Jack ;
    Jack.type = "Dog" ;
    //why do I have to do Jack.setTypeOfAnimal("Dog") ?
    }
    its longer and doesn't make sense. Thank you all

  12. #12
    a guy with long hair Xupicor's Avatar
    Join Date
    Sep 2010
    Location
    Poland
    Posts
    103
    First of all, I'd actually use constructor here.
    Second, you can validate the data in a setter, and decide not to modify the internal variable at all. Or maybe you want only values of 50..100 to be inserted - then you can validate the value in a setter, and for example - if it's < 50, you set 50, if its > 100, you set 100 - or throw exceptions instead. So, you can prevent "illegal" values to be inserted to a variable, on which your class may depend and expect to always be valid.

    To add to it, you can change the name/type of "type" variable, and change your setter/getter accordingly, and yet - you would have no change at all in the code that uses the class. Not that it would be so smart, but possible, and should illustrate the part of the concept.
    Last edited by Xupicor; 09-25-2010 at 08:05 AM.

  13. #13
    Registered User
    Join Date
    Aug 2010
    Location
    Poland
    Posts
    671
    for example i have 2 functions isPrime() and isLoop() or whatever. The variables are local to the functions. Each function cannot see the other functions so I guess they can be referred to as private. But even lets say the functions in isPrime() were public/global, isLoop() and main()
    I don't understand it - give a code snippet because I don't know what is local what is a member.

    Quote Originally Posted by Eman View Post
    [code]
    class Animal
    {
    public:
    void setTypeOfAnimal() ;
    void getTypeOfAnimal() ;

    private:
    int height, weight;
    string type;

    }
    int main()
    {
    Animal Jack ;
    Jack.type = "Dog" ;
    //why do I have to do Jack.setTypeOfAnimal("Dog") ?
    }
    its longer and doesn't make sense. Thank you all
    Access modifiers hide implementation details for the end-user of the class. Google if you want to know more.
    About your code - it still does make sense. Look at your code - type is a string. What if you want to make it an int later? Maybe you will want to remove this field, because you can determine the type of an animal based upon its number of legs, hands etc.

    Getters/setters are evil and should be avoided as much as possible. Let's have a look at the following class:

    Code:
    class Animal {
    private:
        int _NumLegs;
        int _NumHands;
    public:
        int GetNumLegs() const;
        int GetNumHands() const;
    };
    It seems to be a well designed class - the members are private and are accessible through getters. What will you do if you want to get number of all limbs?

    I guess you would call:

    Code:
    int limbs = a.GetNumLegs() + a.GetNumHands();
    Ok, but what if the designer of the class adds a 'tail' field and its getter? You need to change every piece of code that computes number of limbs. The best approach would to be to add a method:

    ComputeNumLimbs() const;

    But I would recommend calling it GetNumLimbs() - word 'Compute' reveals an important implementation detail, telling us it is being computed. We don't care about it - we want to get the number of limbs:

    GetNumLimbs() const;

    The more the object will do on its own the better.

    And the problem is almost gone. Almost - a good designer needs to predict all the possiblities. What if the class is supposed to have a field 'head' or 'cock' in the future?

    EDIT:
    About your code, if you call a method for an animal, it's obvious it's an animal. getType would be enough, we know it is an animal.

    EDIT:
    I wouldn't know but what if for example one of the methods
    IsLeftDown - if I wanted to use it wouldn't I need to know the number of parameters the function can take? So I would still have to know a little bit of what the class does as another programmer,how many parameters what type of argument and stuff -right?.
    That's an everlasting problem of all designers, which does not seem to be solved, since you always need to know at least a bit about the class used.
    Last edited by kmdv; 09-25-2010 at 08:36 AM.

  14. #14
    a guy with long hair Xupicor's Avatar
    Join Date
    Sep 2010
    Location
    Poland
    Posts
    103
    That's an everlasting problem of all designers, which does not seem to be solved, since you always need to know at least a bit about the class used.
    You probably won't use a spoon properly the first time you see it, even if eating with it is such a basic activity. You sure can figure it out, eventually, but it is so much faster to see how others use it, isn't it? That's why there are usually example codes to illustrate how a class/library should be used. Oh, and IntelliSense (whether in Visual Studio, or not) comes to the rescue, giving you the info you seek at hand.

  15. #15
    C++まいる!Cをこわせ! Elysia's Avatar
    Join Date
    Oct 2007
    Posts
    22,169
    Quote Originally Posted by Eman View Post
    I wouldn't know but what if for example one of the methods
    IsLeftDown - if I wanted to use it wouldn't I need to know the number of parameters the function can take? So I would still have to know a little bit of what the class does as another programmer,how many parameters what type of argument and stuff -right?.
    You would need to know that. If you send a mail to someone, the post office doesn't know where to send it unless you tell them, right? The same must be same for functions. So you have to be careful about modifying what a function takes and returns.
    Often this means that when a radical change is made that requires the function signature to change (what parameters it takes and returns, etc), a new function is instead created and the old one marked "deprecated."

    Can some please explain to me the point of access modifiers/specifiers?
    what is the point of making a data member private?
    The point of these is to protect yourself from problems. Maybe you only want someone who uses the class (including yourself) only want to access certain functions. But what if you, by mistake, access members you shouldn't?
    Also it tells us information about members. Which ones are part of the "public" interface, that is, which ones should we concern us about and which ones should we not?
    You could theoretically make everything public. All the concepts would work. But then you can accidentally shoot yourself in the foot by accessing those members.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.
    For information on how to enable C++11 on your compiler, look here.
    よく聞くがいい!私は天才だからね! ^_^

Page 1 of 2 12 LastLast
Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Singleton problems
    By techrolla in forum C++ Programming
    Replies: 16
    Last Post: 01-02-2005, 03:05 PM
  2. Going out of scope
    By nickname_changed in forum C++ Programming
    Replies: 9
    Last Post: 10-12-2003, 06:27 PM
  3. Replies: 4
    Last Post: 03-31-2003, 11:49 PM
  4. [c++] cannot access the ClassView information file
    By vistavision in forum Windows Programming
    Replies: 4
    Last Post: 01-14-2003, 01:31 PM
  5. Special Allegro Information
    By TechWins in forum Game Programming
    Replies: 12
    Last Post: 08-20-2002, 11:35 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21