Thread: A few beginner's questions

  1. #1
    Registered User Megidolaon's Avatar
    Join Date
    Oct 2008
    Posts
    8

    Question A few beginner's questions

    I hail from C# and C++ is confusing me a lot.

    1) I just got an error for putting the visibility identifier before the name of a method (at least I think that was the reason), so it's absolutely mandatory I use private: or public: and then put the methods and attributes after these declarations?
    And private is standard, so I don't need to write it or?

    2) I got an error for defining a method inside the class it belongs to (again, I think so), WTF?
    How can you achieve data encapsulation when half the code of a class isn't part of it but defined globally?
    In all the examples I've seen so far, it was done this way, is that mandatory or just optional?
    And if it's mandatory, how do I write libraries and encapsulate classes in them, where am I supposed to define the methods, so that I can later just call them without any extra code?

    3) Is there any kind of general exception I can catch, that at least tells me some vague info about what happened?
    I only found specific exceptions and adding the throw(...) statement to add in a function's name, but this won't tell me jack about what happened.

    4) The constructor of a class is called without using the new statement?
    What do I use the new statement for? Only for arrays?
    And that means just declaring a variable of a class (and structure/Union,too?) will allocate the necessary memory?

    5) How do I convert from numbers/Boolean into strings and back, is there anything resembling Parse/TryParse functions from C#?
    From what I've read, I can only think of outputting a number/bool into a stringstream and then inputting that back into a string. For the other way around I can only think inputting the string into the number/bool from a stringstream and then maybe using a nested try-catch block to check if it worked.

    Thanks in advance.
    Last edited by Megidolaon; 10-21-2008 at 05:10 AM.

  2. #2
    Registered User C_ntua's Avatar
    Join Date
    Jun 2008
    Posts
    1,853
    1) Yes, you use public: and list everything
    2) You shouldn't get an error. You can define the method in a normal class. There are some issues though. Does that method (function) uses objects from another class? If so you have to check forward declaration and stuff which don't exist (hopefully) in C#. In any case it won't be defined globally, you would probably need the :: scope symbol. Like class::method. Post certain code for more clarifications.
    4) In C++ this is an object:
    Code:
    object O;
    the same way you declare a variable. You can use a constructor like:
    Code:
    object O(a,  b);
    the new keyword dynamically allocates memory.
    In C# this is a reference and not an object:
    Code:
    object O;
    the equivalent thing in C++ is this for a reference:
    Code:
    object& O; //even though you would get an initialization error
    Code:
    object& O = new Object(a,b);
    So, the new is dynamically allocation, without the new is statical allocation. In any way you will have allocated memory.
    5) There should be certain functions that do that. I ll search and post some

    A C++ way is:
    Code:
    std::stringstream ss;
    int t = 123;
    ss << t;
    std::string str = ss.str();
    The opposite:
    Code:
    std::istringstream ss;
    std::string str = "2443"
    int t;
    ss >> t;
    You can also use sprintf(), atoi() and other functions. Google and you will find many results.

    For example I find this:
    Code:
    #include <boost/lexical_cast.hpp>
    #include <string>
    
    try
    {
        std::string text = "152";
        int number = boost::lexical_cast< int >( text );
    }
    catch( const boost::bad_lexical_cast & )
    {
        //unable to convert
    }
    Last edited by C_ntua; 10-21-2008 at 05:21 AM.

  3. #3
    The larch
    Join Date
    May 2006
    Posts
    3,573
    1) Those keywords apply to all methods and variables listed below them (unless you use a different keyword). In classes the default visibility is private, so indeed you can list your private members before the public ones without needing the private keyword.

    2) You may need to post a concrete example.

    3) You can catch std::exception& and see what the what() method of it returns. All standard library exceptions are derived from std::exception and you should also use these (or derive your exception types from them).

    E.g
    Code:
    #include <iostream>
    #include <string>
    #include <exception>
    #include <boost/lexical_cast.hpp>
    
    int main()
    {
        std::string s("10.2");
        try {
            int i = boost::lexical_cast<int>(s);
        }
        catch (std::exception& e) {
            std::cout << e.what() << '\n';
        }
    }
    Even though lexical_cast is not part of the standard but of the boost library, the bad_lexical_cast exception is derived from std::exception, so it can be still caught like that.

    boost::lexical_cast is also probably the best way to convert between other types and strings.

    4) In C++ there are stack (automatic) objects and heap (dynamically allocated) objects. The first ones are deallocated automatically when they go out of scope, the second ones remain until they are deallocated with delete. Both object creation methods have their own uses, but unless you have pressing reasons you should prefer automatic objects (without the new keyword).

    5) One way is to download and use boost. But it can also be done with stringstream (which boost::lexical_cast uses internally). However, streams don't throw exceptions, so you should check the fail bits of the stream after the conversion (and perhaps whether the entire string was converted) to know if it succeeded.
    Last edited by anon; 10-21-2008 at 05:30 AM.
    I might be wrong.

    Thank you, anon. You sure know how to recognize different types of trees from quite a long way away.
    Quoted more than 1000 times (I hope).

  4. #4
    Registered User C_ntua's Avatar
    Join Date
    Jun 2008
    Posts
    1,853
    To make my point more clear about your 4) questions.
    In C# ALL objects go in the heap. They are dynamically allocated.
    In C++ you choose where objects go. If you declare them "normally" the go in the stack. If you use the new keyword the go in the heap (dynamically allocated). C++ does things as they would normally be done in C.

    In C# you have the option of statically allocating or dynamically allocating when you use value types, like int, uint, char etc etc not reference types, like objects.

    This might help: http://www.c-sharpcorner.com/UploadF...5-413b6d348b91

  5. #5
    Registered User Megidolaon's Avatar
    Join Date
    Oct 2008
    Posts
    8
    Thanks a lot!

    I had read something about C++ objects not being passed by reference but by value, though I didn't know all of the data was normally on the stack.

    If you use the new keyword the go in the heap (dynamically allocated).
    I only get errors when using it.

    I tried something like
    Code:
    Object o = new Object();
    As you would in C# and it doesn't work. How would be the correct syntax?

    And is it best to only use pointers to objects (which would mimic C#) so that you can't make the mistake of passing them by value?

    As for defining methods inside their class, my wording was bad. I didn't mean globally but rather that the method body is defined in the namespace, yet outside the class itself:

    Code:
    using namespace std;
    
    class something
    {
    public: 
    	int add(int, int);
    	int multiply(int, int);
    };
    
    int something::add(int a, int b)
    {
    	return a+b;
    }
    
    int something::multiply(int x, int y)
    {
    	return x*y;
    }
    
    void main() 
    {
    . . .
    What I would want to do (and I'm used to in C#) is to put all code that is part of a class between the starting and ending brackets:

    Code:
    class something
    {
    public:
    	int add(int a, int b)
    	{
    		return a+b;
    	}
    
    	int multiply(int x, int y)
    	{
    		return x*y;
    	}
    };
    Also, how do I make static methods (and classes)?
    I tried around and just get more and more errors.

  6. #6
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Quote Originally Posted by Megidolaon
    As you would in C# and it doesn't work. How would be the correct syntax?
    new Object() gives you a pointer to an Object object that is value-initialised. As such, you would write:
    Code:
    Object* o = new Object();
    You also need to use delete when you are done with o, e.g.,
    Code:
    delete o;
    Quote Originally Posted by Megidolaon
    And is it best to only use pointers to objects (which would mimic C#) so that you can't make the mistake of passing them by value?
    No. To avoid passing them by value, make the parameters of the relevant functions take the objects by (const) reference. Of course, in some situations you actually want to pass objects by value, e.g., you want to work on a copy anyway.

    Quote Originally Posted by Megidolaon
    What I would want to do (and I'm used to in C#) is to put all code that is part of a class between the starting and ending brackets:
    You can define member functions inline in the class definition if you wish, so the error is probably a typographical error or something else.

    Quote Originally Posted by Megidolaon
    Also, how do I make static methods (and classes)?
    What did you try? There is no such thing as a static class in C++, as far as I know.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  7. #7
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Code:
    Object *o = new Object();
    As to your class member function definitions, they are no more global than if you put them within the class declaration itself. Functions within the class declaration itself default to inline, but otherwise it's just a matter of "where does it make sense to put this function". They are no more available to anyone outside of the class in either case. Obviously, if you have large functions (10-100 lines), then the function is much better off outside of the class itself, since the class definition gets very cluttered up if you have the lots of code inside it.

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  8. #8
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    And at last: http://cpwiki.sf.net/void_main
    You're picking up bad habits, because void main is undefined. You shouldn't use it.

    Since you seem new to C++, I should give you an advice to actually learn about pointers. You can't avoid them.
    You'll also want to learn the trivial things about syntax, T* vs T * for one (laserlight uses T*, mats uses T *, both are right, and none are wrong): http://www.research.att.com/~bs/bs_faq2.html#whitespace
    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.

  9. #9
    Banned master5001's Avatar
    Join Date
    Aug 2001
    Location
    Visalia, CA, USA
    Posts
    3,685
    Quote Originally Posted by Elysia View Post
    And at last: http://cpwiki.sf.net/void_main
    You're picking up bad habits, because void main is undefined. You shouldn't use it.

    Since you seem new to C++, I should give you an advice to actually learn about pointers. You can't avoid them.
    You'll also want to learn the trivial things about syntax, T* vs T * for one (laserlight uses T*, mats uses T *, both are right, and none are wrong): http://www.research.att.com/~bs/bs_faq2.html#whitespace
    *Bookmarks*

    And it was written, let no one ever forget the post known only as 799191. Which is similar to an old phone number of mine, so I probably will remember it easily

  10. #10
    Registered User Megidolaon's Avatar
    Join Date
    Oct 2008
    Posts
    8
    Thanks once more.
    You can define member functions inline in the class definition if you wish, so the error is probably a typographical error or something else.
    I see, does anyone have a link where I can look up the correct syntax, because all tutorials I've found define the methods outside the class.

    No. To avoid passing them by value, make the parameters of the relevant functions take the objects by (const) reference. Of course, in some situations you actually want to pass objects by value, e.g., you want to work on a copy anyway.
    Do I need an extra variable if I have a normal object and a function that only takes a pointer to such an object?

    What did you try? There is no such thing as a static class in C++, as far as I know.
    I almost finished an rpg battle system in C# and for that I'd have actions like attack or use item as classes.
    Now since they are always the same, regardless of which character/enemy uses them, they should be static so they don't waste unnecessary memory.

  11. #11
    Registered User C_ntua's Avatar
    Join Date
    Jun 2008
    Posts
    1,853
    --Do this:
    Code:
    class A
    {
    public:
       int a;
       void show(int i) {std::cout << a;}
    };
    it compiles normally. As this one:
    Code:
    class A
    {
    public:
       int a:
       void show(int i);
    };
    void A::show(int i) {std::cout << a;}
    I ll make a guess which MAYBE is correct (don't have g++ at the moment to test it).
    Code:
    class A
    {
    public:
       void doNothing(B par) {;}
    };
    class B
    {
       int b;
    };
    The above might not work, because B was declared below A. So you might need this:
    Code:
    class A
    {
    public:
       void doNothing();
    };
    class B
    {
       int b;
    };
    void A::doNothing() {B b();}
    which I believe should work. In C# you don't have to worry about these thinks

    --No, you don't need an extra variable. I don't fully understand what you mean. In C++ you can do MORE than C# when it comes to passing objects to methods. You can do all the below:
    Code:
    void add(obj o);
    void add(obj& o);
    void add(obj* o);
    Now, in the first two you will pass an object normally, as in C#. Like:
    Code:
    obj o();
    add(o);
    in the third method you need to pass a pointer. Like:
    Code:
    obj o();
    obj* ptr_o = &o;
    add(ptr_o); //or just add(&o);
    The first two methods differ only on the HOW the object is passed. Everything else is as in C#. The C# way is the second, passing the object by reference. The first makes a copy of the object. It is like passing an object, making a copy and using the copy.

    --Well, you can make a method static. Like:
    Code:
    class attack
    {
    public:
       int damage;
       static use() {...}
    };
    ...
    int main() {
    character ch1(), ch2();
    attack.use(ch1, ch2);

  12. #12
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Quote Originally Posted by C_ntua
    The above might not work, because B was declared below A.
    That's true, but one can just move the definition of B before the definition of A.

    Quote Originally Posted by C_ntua
    Now, in the first two you will pass an object normally, as in C#. Like:
    fyi, this declares a function named o that takes no arguments and returns and returns an obj:
    Code:
    obj o();
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  13. #13
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    Quote Originally Posted by C_ntua View Post
    I ll make a guess which MAYBE is correct (don't have g++ at the moment to test it).
    Code:
    class A
    {
    public:
       void doNothing(B par) {;}
    };
    class B
    {
       int b;
    };
    The above might not work, because B was declared below A. So you might need this:
    This is incorrect, because it takes a B by-value and B is not yet defined. It doesn't even work with a forward declaration.
    You need to take it by pointer or reference with a forward declaration or define B before A.

    Code:
    class A
    {
    public:
       void doNothing();
    };
    class B
    {
       int b;
    };
    void A::doNothing() {B b();}
    which I believe should work. In C# you don't have to worry about these thinks
    And as laserlight pointers out, don't use () on objects with a constructor that takes no arguments. It's a declaration.
    The correct code is
    Code:
    B b;
    --Well, you can make a method static. Like:
    Code:
    class attack
    {
    public:
       int damage;
       static use() {...}
    };
    ...
    int main() {
    character ch1(), ch2();
    attack.use(ch1, ch2);
    This is also incorrect. The correct syntax to call a static method is:
    attack::use
    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.

  14. #14
    Registered User C_ntua's Avatar
    Join Date
    Jun 2008
    Posts
    1,853
    Really, sorry for my mistakes :S
    Kind of answered quick...

    Just to mention though that maybe you could have:
    Code:
    class A
    {
    public:
       void doNothing(B par) {;}
    };
    class B
    {
       int b;
       A a;
    };
    so you know.... I believe that was the cause that the function HAD to be outside

  15. #15
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    You can't have that because
    a) A references B with pass-by-value which is defined later.
    b) B relies on A, which creates a circular reference.
    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.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Beginner's Questions
    By bjl in forum C++ Programming
    Replies: 4
    Last Post: 01-31-2008, 06:56 AM
  2. A very long list of questions... maybe to long...
    By Ravens'sWrath in forum C Programming
    Replies: 16
    Last Post: 05-16-2007, 05:36 AM
  3. Several Questions, main one is about protected memory
    By Tron 9000 in forum C Programming
    Replies: 3
    Last Post: 06-02-2005, 07:42 AM
  4. Trivial questions - what to do?
    By Aerie in forum A Brief History of Cprogramming.com
    Replies: 23
    Last Post: 12-26-2004, 09:44 AM
  5. questions questions questions.....
    By mfc2themax in forum A Brief History of Cprogramming.com
    Replies: 1
    Last Post: 08-14-2001, 07:22 AM