Sereious Question: Best way to learn C++

This is a discussion on Sereious Question: Best way to learn C++ within the C++ Programming forums, part of the General Programming Boards category; Ok... seriously... what is the best way to go about learning c++? I've looked at the books list and have ...

  1. #1
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547

    Sereious Question: Best way to learn C++

    Ok... seriously... what is the best way to go about learning c++?

    I've looked at the books list and have even been into a couple of them.
    I've read quite a few online tutorials.
    So it's not like I'm asking a superficial question...

    Where I always end up the bug (and never the windshield) is classes...

    I get the general syntax, it's very pascal/c ish... but for some reason I just haven't been able to get my head around OOP code... It's like as soon as I see all these classes inheriting from other classes and being constructed and destructed, the books, manuals, etc. might as well be written in Klingon secret code...

    Big question... What exactly is a "class"?
    Second question... Why do I need them?

  2. #2
    Registered User
    Join Date
    Jan 2011
    Posts
    2

  3. #3
    -bleh-
    Join Date
    Aug 2010
    Location
    somewhere in this universe
    Posts
    452
    For class. Think of C style struct. It contain some member variables right? Not completely correct, but a class is more like a C struct but it also contains member functions(or interface). When the member variables are made private in the class, it prevent the users from changing them haphazardly. You can't even access them for output. The only way to initialize these variables is through the constructor which is a special member function. Only member function of the class can access the private variables and alter them. This prevent you to alter the data because you like to. You have to change the data in the specific way that is defined by the member functions. Or access the data in the specific way. Data that you should not see or don't have to see will be hidden from you. Hiding data from the users is just the concept of encapsulation. Imagine the car is your class. The user interface in the car(or member function) is your steering wheel gas pedal etc. These interfaces tell the car how to turn and accelerate. You don't have to worry about the internal structutre of the combustion engine, gearshift, electrical systems ( private member variables).

    Inheritance just gives you different flavor of cars: sport cars, trucks, NASCAR.
    Template is more like trying to design a onesize fit all engine. Not really the best concept so you'll have specializations.
    "All that we see or seem
    Is but a dream within a dream." - Poe

  4. #4
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    Quote Originally Posted by Firat View Post
    Ok, I've read that before and I just went through it again now.... I get the concept of "classes"... blobs of encapsulated data and code that do more or less related tasks. There are hundreds of tutorials to tell me what it is. What I need to know is where and when...

    In all my years of programming I've never once found myself sitting here, staring at the screen thinking: "I really NEED an object (or class) here."... never, not once. So the mystery remains, what is this for and why do I need it?

    Maybe a hypothetical will help... Lets say I'm doing a very simple text-chat program.
    This is going to require...
    1) Network initialization
    2) Contact out
    3) Accept contact in
    4) Displaying text
    5) Reading the keyboard
    6) Sending Datagrams
    7) Receiving Datagrams
    8) Close contact

    What classes would this reaquire and why?

  5. #5
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    Quote Originally Posted by nimitzhunter View Post
    For class. Think of C style struct. It contain some member variables right? Not completely correct, but a class is more like a C struct but it also contains member functions(or interface). When the member variables are made private in the class, it prevent the users from changing them haphazardly. You can't even access them for output. The only way to initialize these variables is through the constructor which is a special member function. Only member function of the class can access the private variables and alter them. This prevent you to alter the data because you like to. You have to change the data in the specific way that is defined by the member functions. Or access the data in the specific way. Data that you should not see or don't have to see will be hidden from you. Hiding data from the users is just the concept of encapsulation. Imagine the car is your class. The user interface in the car(or member function) is your steering wheel gas pedal etc. These interfaces tell the car how to turn and accelerate. You don't have to worry about the internal structutre of the combustion engine, gearshift, electrical systems ( private member variables).

    Inheritance just gives you different flavor of cars: sport cars, trucks, NASCAR.
    Template is more like trying to design a onesize fit all engine. Not really the best concept so you'll have specializations.
    Ok, I get that... thanks.

    Now... as a programmer I would never --not ever-- allow a user to modify a variable directly. Users don't have direct access to variables in C... so what's the advantage here? Seems to me all you're doing is hiding it from *yourself*...

    The idea of not having to understand the guts of an engine to drive a car has been handed to me before... However; if I'm writing the classes and the program they're in I do understand what's under the hood so once again it just seems like I'm really just hiding stuff from myself.

    Even in a large programming pool where multiple groups of multiple people each are working on a common project I still don't see the value in hiding stuff....

    ?????

  6. #6
    Registered User
    Join Date
    Aug 2003
    Posts
    1,197
    How about forcing yourself to do some personal project using OOP? And do this at the same as you read about classes and such.

    Inheritance and polymorphism and all that can be confusing but really, I think the best way to wrap your brain around it is by doing.

    But the beauty is that when you are using it you dont have to understand how the internals work. This is where inheritance and polymorphism comes in. With this you can say "This car has an engine", it doesnt care how the engine operates and so on. Now you can have other people actually implement different types of engines (electrical, diesel, gas hybrid and so on) and as long as they implement the methods you use in your car (throttle, start, stop etc) you dont really care what the engine does internally (while working on the car).

    This allows you to focus on working on implementing the functionality with a car, without caring how the engine actually operates.

    An even better example are controls used in GUI. Say you have a class Control. This class provides methods such as OnPaint, SetName, GetName, OnGetFocus, OnLoseFocus, Focus, UnFocus, OnClick and so on. Now from this you can derive a Button that shows some text. You can then derive another button, ImageButton that instead of showing text shows an image. But when you add these to the actual Window you dont care if its a Button or an ImageButton or something else. You only care that it is a Control and thus provides OnPaint for drawing it. This also allows other people to use Control and create their own controls and so on.

    Or to give a third example which is very close to my current project. Say you have an application that needs to get data from somewhere. You thus have a DataProvider class that exposes methods for getting data (GetName, GetNameCount and so on). As long as these methods are doing their job the application doesnt have to care where the data is fetched from, wether it be a local file or a remote database on the other side of earth. And you can relatively easy provide both of these functionalities simply by changing the way the DataProvider class is implemented internally.
    Last edited by Shakti; 01-09-2011 at 05:33 AM.

  7. #7
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    Quote Originally Posted by Shakti View Post
    How about forcing yourself to do some personal project using OOP? And do this at the same as you read about classes and such.
    My plan exactly... I was intending to spend today cleaning and sorting files on my main machine and getting ready to put in fresh copies of PellesC (which I am very happy with) and then get setup for C++... I'm thinking the SDK for Win7 (which includes the VC9 compiler) and Code::Blocks for the IDE... All in their own partition. Once that is done, I plan to learn C++ with no excuses this time...

    I will pour through tutorials etc. but I'm still clear as mud on how you decide when to use a class and when to use procedural code...

    Inheritance and polymorphism and all that can be confusing but really, I think the best way to wrap your brain around it is by doing.
    I agree... you learn programming by programming. But I'm so blocked on this OOP stuff that I really do need some help to get past it. As I've said before it's the When and Why that are leaving me stumped...

  8. #8
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    An even better example are controls used in GUI. Say you have a class Control. This class provides methods such as OnPaint, SetName, GetName, OnGetFocus, OnLoseFocus, Focus, UnFocus, OnClick and so on. Now from this you can derive a Button that shows some text.
    "Derive"? How? Can you show an example?

  9. #9
    -bleh-
    Join Date
    Aug 2010
    Location
    somewhere in this universe
    Posts
    452
    Here's an example where it may come in handy. Just a simple operation of adding two vectors element by element. Not the best code, it's almost 5am, so you'll have to excuse me.

    Code:
    // C code
    int* add(int * x, int * y,const int n , const int m)
    {
    if ( n == m)
    {
      int *z = new int[n];
      for ( int i = 0 ; i<n ; i++)
        z[i] = x[i] + y[i];
      return z; 
    }
    }
    
    const int n = 10; 
    int a[10] = {something};
    int b[10] = {something};;
    int * sum; 
    sum  = add(a,b,n,n);
    
    delete [] sum;
    You'll probably won't do that: having to remember to deallocate memory for something that got allocated inside a function. See that each vector has its own lengths. It's good to keep length of the array along with its elements. You can do so with struct, but the add function will become a bit wild. With a class, you can spend sometime to design the class vector, such that when it comes time to implement, your user-defined type vector can behave just as any fundamental type.
    Code:
    // c++ using class
    class Vector
    {
    private:
      int num; 
      int *elem;
    public:
      Vector():num(0),elem(0) {}
      Vector(int n):num(n)
      {
        elem = new int[num];
        for ( int i = 0 ; i < num ; i++)
          elem[i] = 0;
      }
      Vector(int * a, int n = 0): num(n);
      {
        for ( int i = 0 ; i < num; i++)
          elem[i] = a[i];
      }
      ~Vector() {delete [] num} 
      
      Vector operator+(const Vector & in) const
      {
        if ( num == in.num)
          {
    	int temp[num];
    	for( int i = 0 ; i < num ; i++)
    	  temp[i] = elem[i] + in[i];
    	return Vector(temp,num); 
          }
        else
          exit(0); 
      }
      void operator=(const Vector & in)
      {
        num = in.num;
        if(elem == 0 )
          elem = new int[num];
        else
          {
    	delete [] elem;
    	elem = new int[num];
          }
        for ( int i = 0 ; i < num ; i++)
          elem[i] = in[i]; 
      }
      operator-;
      operator++;
      operator--;
      operator*;
      operator*=;
      operator+=;
          
    };
    
    int main()
    {
      Vector a({some_array},10);
      Vector b({some_array},10);
      Vector c;
      
      c = a+b; 
    }
    First, notice the destructor ~Vector, it do the deallocation for me. I don't need to remember to call "delete". Even though the class is kinda of long, the implementation is simple. Adding two vector using the same syntax as adding two fundamental type. So if you're a user, and you need to add two vector element by element, you don't really need to check whether you'll have to use array or pointer to represent the array; don't have to remember to deallocate memory. Class let you design your own data type that can behave as close to the fundamental types as possible and more.
    "All that we see or seem
    Is but a dream within a dream." - Poe

  10. #10
    Registered User blackcoder41's Avatar
    Join Date
    Jan 2010
    Location
    Philippines
    Posts
    14
    When?
    I guess when you need to represent a real world object in terms of programming. Also to divide the task. Just like the car example given above, each programmer could focus on different task like engine, steer wheel, etc just like in the real world.

    Why
    Because it could be easier. Because it's the preferred way of doing things in an OOP language.

    Though I could be wrong

    PS: You might want to try Java first if you want.

  11. #11
    Registered User whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    7,532
    Quote Originally Posted by CommonTater View Post
    Ok, I get that... thanks.

    Now... as a programmer I would never --not ever-- allow a user to modify a variable directly. Users don't have direct access to variables in C... so what's the advantage here? Seems to me all you're doing is hiding it from *yourself*...

    The idea of not having to understand the guts of an engine to drive a car has been handed to me before... However; if I'm writing the classes and the program they're in I do understand what's under the hood so once again it just seems like I'm really just hiding stuff from myself.

    Even in a large programming pool where multiple groups of multiple people each are working on a common project I still don't see the value in hiding stuff....

    ?????
    Well any class you write, you're going to be familiar with it.

    I'm unlikely to be the best OOP guy on the board but I will give a shot at a very brief explanation.

    One way to think about OOP conceptually is through the idea of messaging. Object-oriented programming is about objects communicating with one another, sharing messages, in order to get the job done. The messages they send basically have to do with their state (the data part of a data structure). You want to make other objects in your program use the interface of a class, so this is why you hide away the state.

    So to take an example of your chat program, you might design several classes that would have been records in procedural programming. You could have a Window class to display messages to the end user and offer a typing area, and other controls: basically to serve as a UI. You would also model a ContactList at least.

    So if you use a Window to message someone, you'd deal with the following messages: the Window shares the recipients with the ContactList and the ContactList would check who's online. Then the ContactList might call some network functions and pass back some handles to the Window, or however you design it. Finally the Window sends the message across the network. When you're done talking, close the Window, and it will send a quit message to ContactList, which prompts the program to update your status, hang up on the network and die.

    So it works pretty much the same way a procedural program would, but you have to think about what kind of information you need to share with other objects. The idea is by breaking it up into objects you have a shot at getting the computer to manage a thing or an idea. If you later wanted to add a feature you could just add a class representing said feature.

    If you think I made it sound too easy you are absolutely right, but hopefully it sounds less like madness now.

  12. #12
    Registered User
    Join Date
    Aug 2003
    Posts
    1,197
    Here is a small example of my GUI stuff i talked about
    Code:
    #include <iostream>
    
    class Control
    {
    public:
    	virtual void OnPaint() { std::cout << "Control here painting..." << std::endl; }
    };
    
    // Derive from Control "Button IS A Control"
    class Button: public Control
    {
    	int x;
    public:
    	Button(int _x)  { x = _x; }
    	// Override OnPaint with our own
    	virtual void OnPaint() { std::cout << "Button here painting... oh and x = " << x << std::endl; }
    };
    
    // Derive from Control "ImageButton IS A Control"
    class ImageButton: public Control
    {
    public:
    	// Overload (override) OnPaint with our own
    	virtual void OnPaint() { std::cout << "ImageButton here painting..." << std::endl; }
    };
    
    void paint(Control *c)
    {
    	c->OnPaint();
    }
    
    int main()
    {
    	Control *c = new Control();
    	Control *cb = new Button(10);	// Notice how we say this is a pointer to a control
    	Control *cib = new ImageButton();
    
    	// Notice how paint doesnt care about which of the above we send in
    	// because they are all controls, just different implementations of it
    	paint(c);
    	paint(cb);
    	paint(cib);
    
    	delete c;
    	delete cb;
    	delete cib;
    }
    Really simplified derivation can be used to say "This class IS A <some other class>" and its then said to inherit from <some other class>.

  13. #13
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    Quote Originally Posted by whiteflags View Post
    One way to think about OOP conceptually is through the idea of messaging. Object-oriented programming is about objects communicating with one another, sharing messages, in order to get the job done.
    Ok... so following up on what you've said below...
    What messages would the contact list get/send with the message class... and how would it send them?

    Or... am I confusing "windows messages" (WM_COMMAND, etc.) with something else?

    So to take an example of your chat program, you might design several classes that would have been records in procedural programming. You could have a Window class to display messages to the end user and offer a typing area, and other controls: basically to serve as a UI. You would also model a ContactList at least.

    The messages they send basically have to do with their state (the data part of a data structure). You want to make other objects in your program use the interface of a class, so this is why you hide away the state.
    Ok that one I get... If I have a contact list, and want to talk to a specific user... I would include a method CallUser(username) in the class... To maintain it, I would have adduser, deletuser, listusers, etc... like in C... but the way it does those things is barracaded against inproper usage?

    So if you use a Window to message someone, you'd deal with the following messages: the Window shares the recipients with the ContactList and the ContactList would check who's online. Then the ContactList might call some network functions and pass back some handles to the Window, or however you design it. Finally the Window sends the message across the network. When you're done talking, close the Window, and it will send a quit message to ContactList, which prompts the program to update your status, hang up on the network and die.
    Clear as mud. It sounds like Classes intercommunicate on some level I'm not understanding...

    So it works pretty much the same way a procedural program would, but you have to think about what kind of information you need to share with other objects. The idea is by breaking it up into objects you have a shot at getting the computer to manage a thing or an idea. If you later wanted to add a feature you could just add a class representing said feature.
    Ok... modularity... a Pascal concept I understand. In procedural pascal you would create a unit, the Interface would contain function prototypes and public data declarations. The Implementation would house the actual code and any private variables... kinda like .h and .c do in C code... This I think I get... you can use the public and private parts of a Class in a similar fashion...

    If you think I made it sound too easy you are absolutely right, but hopefully it sounds less like madness now.
    Believe me... I see nothing easy here...

  14. #14
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    Quote Originally Posted by nimitzhunter View Post
    First, notice the destructor ~Vector, it do the deallocation for me. I don't need to remember to call "delete". Even though the class is kinda of long, the implementation is simple. Adding two vector using the same syntax as adding two fundamental type. So if you're a user, and you need to add two vector element by element, you don't really need to check whether you'll have to use array or pointer to represent the array; don't have to remember to deallocate memory. Class let you design your own data type that can behave as close to the fundamental types as possible and more.
    Ok... cool... I'm not following the syntax yet, but I get the concept... basically that of creating a combination of data and function and using it wholecloth to achieve a large result.

  15. #15
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    Quote Originally Posted by Shakti View Post
    Here is a small example of my GUI stuff i talked about
    Code:
    #include <iostream>
    
    class Control
    {
    public:
    	virtual void OnPaint() { std::cout << "Control here painting..." << std::endl; }
    };
    
    // Derive from Control "Button IS A Control"
    class Button: public Control
    {
    	int x;
    public:
    	Button(int _x)  { x = _x; }
    	// Override OnPaint with our own
    	virtual void OnPaint() { std::cout << "Button here painting... oh and x = " << x << std::endl; }
    };
    
    // Derive from Control "ImageButton IS A Control"
    class ImageButton: public Control
    {
    public:
    	// Overload (override) OnPaint with our own
    	virtual void OnPaint() { std::cout << "ImageButton here painting..." << std::endl; }
    };
    
    void paint(Control *c)
    {
    	c->OnPaint();
    }
    
    int main()
    {
    	Control *c = new Control();
    	Control *cb = new Button(10);	// Notice how we say this is a pointer to a control
    	Control *cib = new ImageButton();
    
    	// Notice how paint doesnt care about which of the above we send in
    	// because they are all controls, just different implementations of it
    	paint(c);
    	paint(cb);
    	paint(cib);
    
    	delete c;
    	delete cb;
    	delete cib;
    }
    Really simplified derivation can be used to say "This class IS A <some other class>" and its then said to inherit from <some other class>.
    Now this one I think I got! Basically you "derive" as a means of customizing.... ???

Page 1 of 5 12345 LastLast
Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Fmod question
    By spadez in forum C Programming
    Replies: 2
    Last Post: 04-17-2009, 05:26 PM
  2. another do while question
    By kbpsu in forum C++ Programming
    Replies: 3
    Last Post: 03-23-2009, 12:14 PM
  3. Am I too late to learn programming?
    By maccat in forum A Brief History of Cprogramming.com
    Replies: 17
    Last Post: 02-17-2009, 07:49 AM
  4. Same old beginner question...
    By Sharmz in forum C Programming
    Replies: 15
    Last Post: 08-04-2008, 11:48 AM
  5. Very simple question, problem in my Code.
    By Vber in forum C Programming
    Replies: 7
    Last Post: 11-16-2002, 02:57 PM

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