I just cant get OOP programming

Pages: 12
I try learning OOP but i just cant see where it fits in , anyone got sum tips
What do you mean exactly?

Do you not know when to use OOP?
That's one of my concerns , i dont see why and where i should use it
The idea behind OOP is to take a large, complicated job and break it into smaller, easier to manage jobs. It's often difficult for people to grasp because they just think of their program as a whole, and not really the individual parts of it. They'll often just try to tackle the entire program in one go, rather than break it up first.

And that's fine for smaller programs, but it becomes unwieldly and very difficult for larger programs.

The idea is to create classes that are ignorant of the world around them. By which I mean they don't know anything about the program as a whole. All they know is how to be what they represent. These classes can be more easily used as "building blocks" on which the more complicated "big picture" logic can be built.

OOP can be reasonably applied to most situations. Rather than giving example of when to use it, maybe you could propose a problem and I could illustrate how OOP might be a useful approach to that problem.
Last edited on
If you're scandinavian (which i highly doubt you are) the book "C++ Direkt" by Jan Skansholm has a very in-depth discussion on OOP, from analysis to design, to implementation and programming.

It's well suited for beginners to intermediate (the time whereas you haven't yet completely understood OOP) programmers, otherwise i'd recommend checking out the book recommendations wherever they now are, on this website. Many of those have some clear teachings of OOP.
I'm probably part Scandinavian. Can I read it?
Om jag undrar om du kan prata svenska, vad säger du då?

If you can answer that question, then yes - you can :)
Well, "Svenska" can be "Sweden" or "Swedish" (I think it can mean both; like Suomi can mean Finland or Finnish); "du kan" is probably "you can" so I'd guess "om" is "if" and I'm fairly sure "jag" is "you". I'd guess the first part of the sentence (using the comma as a separator) is something like "If you can speak Swedish" ("speak" is "parle" in French and "prata" looks like "parle" (given both languages have influence from Latin, I'd say that's a fair assumption)).

I would guess that the second part of the question is "do you speak it?" or similar; so I'm going to guess the question is "You can read it if you speak Swedish, do you speak it?"

The answer, unfortunately, is no.

Also; you live in Ostersund? I've been there; in 2004, I can't remember when but I would hazard a guess at June. It was summer anyway, because I recall that the sun didn't set until about 2am.

I think I'm part Danish judging by the Jutish immigration (or was it an invasion? I don't remember) to the part of England I live in; probably between 800 and 1066 AD although I really have no idea...

My surname is Anglo-Saxon, anyway; so I'm definitely of Germanic descent.

Edit: Google's translator thinks it's this:
If I was wondering if you could speak Swedish, what do you do?

I think my guess is more accurate (human intuition > machine translation).
Last edited on
Thanks guys it makes sense now , anyone have an example of what type of program can be done using classes
Disch what about a program that calculates area of different shapes eg. Triangle , square etc.
"You can read it if you speak Swedish, do you speak it?"


Fantastic! It's not literally correct, but you must be some kind of grammar freak to have understood that either way, you were so very very close.

"If I'm wondering if you can talk swedish, what do you answer?"-ish :)

@IntMain.
Yes, let's say you want to create a calculator. You begin by analysing how you want it to work, look, whatever. Next stage is to make some crude model of the program. With some few objects (building blocks) you start defining what each calculation (area of a triangle for example) does.

Once you've got all these objects done, you simply put them together - and you've got yourself a very very simple objectoriented program...

Hmm, my explanation didn't work out very well. Oh well, let's see if someone else will have a go at it :D
Thanks Angelhoof for trying to explain and i am not swedish but i once had a crash on a very beautiful swedish girl and oh it did not work out
IntMain wrote:
Disch what about a program that calculates area of different shapes eg. Triangle , square etc.


This is a common homework problem, actually. I was hoping for more of a real world, non-trivial example since that's where OOP really shines... but okay.

To do this in an OOP fashion, you could create classes for each kind of shape. The classes would focus on just "being" that shape and doing things that the shape would do. They wouldn't be aware of the overall program.

Here's a very simplistic example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#include <iostream>
using namespace std;

class Rectangle
{
public:
  int width;
  int height;

  Rectangle(int w,int h)
    : width(w)
    , height(h)
  {}

  int GetArea()
  {
    return width * height;
  }
};

int main()
{
  int w, h;
  cout << "Give me a width:  "
  cin >> w;
  cout << "Give me a height:  "
  cin >> h;

  // make the Rectangle based on the given w/h
  Rectangle rect(w,h);

  // print the area
  cout << "The area of the rectangle is:  " << rect.GetArea();

  return 0;
}


Of course you could look at that and say:

John Q Programmer wrote:
well that's stupid, why bother with that Rectangle class if I could just cout w*h. Wouldn't that be simpler?


And the answer for that (in this case) is yes. That would be simpler for the overall program. But again that's really only because this is a trivial problem. OOP is better designed to tackle more complex problems.

OOP in general usually requires you write more code, which is why it seems useless for smaller projects.

The flip side of that is that is that it makes the code you write simpler because it only has to focus on one very specific task. So it comes down to a bit more code that is overall simpler vs. a bit less code that is convoluted and confusing.

Here's a less trivial program. See my notes afterwards:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
/*
This program's goal is to do the following:

1)  ask the user what type of shape they want to create.


2)  the program will then ask the user for information about the shape
     based on what type of shape they chose.  Different types of shapes would
     need different information.  For example a square would need a length of one of its sides,
     a rectangle would need a width and a height, a circle would need a radius, etc.

3)  the program will then print the area of the shape
*/

#include <iostream>
#inclust <string>
#include "shapes.h"  // contents of this header intentionally
                     //   omitted, see notes below

using namespace std;

int main()
{
    string userinput;
    Shape* shape;
    while(true)
    {
        // ask the user which type of shape they want
        cout << "What type of shape do you want?";
        getline(cin,userinput);
        
        // generate a shape based on their input
        shape = Shape::Generate(userinput);
        
        // if they didn't specify a valid shape, keep looping until
        //  they do
        if(!shape)
            cout << "You entered an invalid shape.  Please try again.\n";
        else
            break;  // break out of infinite loop to proceed with program
    }
    
    // get the dims for the chosen shape
    shape->GetDimsFromUser();
    
    // print the area of the shape
    cout << "The area is:  " << shape->GetArea();
    
    // cleanup and exit
    delete shape;
    return 0;
}


Note the mysterious "header.h" which I didn't include (I didn't include it because it's not really the point, and I'm trying to keep the example small).

This magical "Shape" class does all of the real work. This makes the overall logic of the program very simple and very easy to follow. That's the point with OOP. To keep the logic doing specific, easy to follow things by splitting the job into smaller parts.
Show us some example about an traffic simulation^^... (edit: joke :P... or maybe not :/)...

I - ashamingly - admit, that I do have many problems concerning OOP implementation styles, too...

For example my server and client programs I did create...:
I have multiple classes which used to be managers for all kind of stuff (e.g. Winsock (send recv), MessageControl(The heart of it all), etc)...

But I do not really know how to connect them efficiently...
I am always thinking, that some of them should contain others... but all I have are managers, that keep pointers of other managers they need to interact with...

The manager, that uses manages another class directly is the window control, which got a map of ChatWindows (class, too)...

And no inheritence anywhere O?o...

So maybe I did it the right way, but maybe not...

May You show us some more complex example of how those classes we create from the "abstract world" may interact with each another the "right" way?...

Last edited on
I'd find that useful too; although maybe it would be better for someone to write an article on OOP...
Thanks disch you must be a c++ guru hey? , i kinda get what your saying , but then how come people can write an OS with C it has no classes right? ,
Any program that can be written using OOP can be written without using it. C is just as Turing-complete as C++ is, meaning that anything C++ can do, C can also do. OOP is just supposed to make it easier.

Edit: I win!
Last edited on
OOP is mostly just a means of organizing your code. As are functions.

EDIT: Dang.

-Albatross
Last edited on
May You show us some more complex example of how those classes we create from the "abstract world" may interact with each another the "right" way?...


The trick is to have the "lower", more basic classes not be aware of the "higher" more complicated ones. The basic classes are the foundation, and from there you stack upwards. If your basic classes are aware of the classes using them, then your program quickly becomes entangled in hard to maintain interdependencies.

Admittedly, I haven't done much networking stuff, but I'd probably approach it like so:

abstract class Connection which represents a network connection between this computer and "something else" (what you're connected with doesn't matter, as it's abstract)

Since the class is abstract, it wouldn't really do anything. However it would have pure virtual functions to Send and Receive data, and other things you might need.

class SingleConnection : public Connection which represents a connection between this computer and one other computer

SingleConnection would probably contain most of the networking nitty gritty. Establishing the connection and actually sending/receiving information and whatnot.

class GroupConnection : public Connection which represents a connection between this computer and multiple other computers.

Internally this class would probably contain a std::list<Connection*> to represent all of the other computers connected to. Send() would just send the data to all connections, and Receive would listen for/receive data from all connections.

class ChatClient which represents a chat client. Internally this would probably just have a SingleConnection, and would translate intuitive things like, lines of text, request for a list of chatrooms, etc into raw data to be transmitted. Basically the interface for ChatClient would be more intuitive for a chat program, whereas SingleConnection would be more "raw" and generic.

ChatClient could also have multiple Connections if you want the user to join multiple servers at once, or directly connect to other users for PMs or something.

Maybe that could even be broken down more. Like maybe have a ChatConnection which does the translating, and then have ChatClient which has a series of ChatConnections.

class ChatServer which represents the server. Internally this would seperate the connections into logical groups. For instance it might have a GroupConnection for each chatroom on the server, and a bunch of SingleConnections to represent all of the users connected to this server. That kind of thing.

It would also translate the raw messages into something comprehensive, and direct them where they need to go.

Note that this should probably be further broken down. For example ChatServer could contain a series of ChatRooms... or something like that.



The key here is that it builds up. SingleConnection doesn't need to know that it's working with a chat program. It only needs to be concerned about sending and receiving data over a network.

ChatClient doesn't need to know how to send/receive data over a network, it can just use the SingleConnection interface to do all of that.

etc, etc.


IntMain wrote:
i kinda get what your saying , but then how come people can write an OS with C it has no classes right?


You can write OOP in C. I'm sure all modern OS's employ OOP concepts in their code, regardless of what language they were coded in.

The C++ language features just make OOP easier to do. But you can have the same constructs without them.

(Though I guess this depends on how strictly you define "OOP". I remember getting into an argument on this forums about that before)
Thanks Disch, that was an excellent and very useful summary.
Pages: 12