CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Page 1 of 3 123 LastLast
Results 1 to 15 of 34

Thread: Java to C++

  1. #1
    Join Date
    May 2009
    Posts
    28

    Java to C++

    Dear All,
    I m new to C++ and am transitioning from Java. I m comfortable with the principles of OOP, which I learnt along with Java.

    Can someone point to a quick reference guide, online or a book? I dont want to start with a beginner's book; also, last few days' experience taught me that I can get lost in much of the complexities of VC++ if I dont pick up the right resource.

    If I may ask some relevant questions:
    1. How are arrays of objects dealt with in C++? I ran into this problem in my project where I had to use an array of object rather than a single object. The single object was declared in Header file. Can arrays be declared in header files too? Can they be instantiated as well?

    2. Much of my confusion exists because I tend to think of the header files as C++ equivalent of interface files in java. In java interfaces, I we used to declare constants, abstract classes etc. We do similar stuff in C++ header files as well. Where do we draw the line?

    Thanks in advance!
    SG

  2. #2
    Lindley is offline Elite Member Power Poster
    Join Date
    Oct 2007
    Location
    Seattle, WA
    Posts
    10,895

    Re: Java to C++

    Quote Originally Posted by sgiri1981 View Post
    Dear All,
    I m new to C++ and am transitioning from Java. I m comfortable with the principles of OOP, which I learnt along with Java.
    You should make sure you learn generic programming for C++. While C++ also supports OOP, generic approaches are generally more widely useful since the language doesn't use a "God object" design which everything inherits from.

    If I may ask some relevant questions:
    1. How are arrays of objects dealt with in C++? I ran into this problem in my project where I had to use an array of object rather than a single object. The single object was declared in Header file. Can arrays be declared in header files too? Can they be instantiated as well?
    An array is not an object like it is in Java. It's simply a block of memory somewhere that has objects in it. If you want to treat an array as if it's an object, use std::vector.

    Generally speaking you can declare anything you want in a header file (using the extern keyword in the case of variables), but you have to define everything in one (and only one) source file.

    2. Much of my confusion exists because I tend to think of the header files as C++ equivalent of interface files in java. In java interfaces, I we used to declare constants, abstract classes etc. We do similar stuff in C++ header files as well. Where do we draw the line?
    There are some similarities. The first thing to realize is that #include statements are like pasting the entire contents of the reference file in place. So anything you put in a header file will appear in every source file that includes it. This can cause linker errors if you define something in a header file rather than just declaring it. (There are exceptions: inline functions, constants, etc.)

  3. #3
    Join Date
    Jan 2008
    Location
    California, USA
    Posts
    822

    Re: Java to C++

    Quote Originally Posted by sgiri1981 View Post
    Dear All,
    I m new to C++ and am transitioning from Java. I m comfortable with the principles of OOP, which I learnt along with Java.

    Can someone point to a quick reference guide, online or a book? I dont want to start with a beginner's book;
    Hello sgiri1981
    I think you should reconsider about that and learn C++ as if you knew nothing about it.

  4. #4
    Join Date
    Jan 2006
    Location
    Singapore
    Posts
    6,765

    Re: Java to C++

    Quote Originally Posted by sgiri1981
    Can someone point to a quick reference guide, online or a book? I dont want to start with a beginner's book;
    Considering that you have a programming background, I recommend Accelerated C++: Practical Programming by Example by Koenig and Moo.
    C + C++ Compiler: MinGW port of GCC
    Build + Version Control System: SCons + Bazaar

    Look up a C/C++ Reference and learn How To Ask Questions The Smart Way
    Kindly rate my posts if you found them useful

  5. #5
    Join Date
    Nov 2006
    Posts
    1,611

    Re: Java to C++

    I second laserlight's book recommendation (beat me to it).

    potatoCode has a point, but I'd also add that a great many have come to C++ from that perspective, and Java/Python/C# are often intentionally taught first because the OOP/OOD concepts are similar in the basics.

    Yet, I must agree with potatoCode's basic point with this observation. Many Java programmers start learning C++, then after some time begin to complain about the language with constant comparisons of how much easier/productive/better things were in Java (C#, whatever the source).

    C++ has a different use in the industry compared to Java, despite the apparent overlap. You may have been attracted to C++ knowing this already. It's important to keep in mind that it aims to control the underlying machine from a different perspective. Java and similar languages give leverage to developers by removing many of the underlying machine mechanics, like pointers, memory allocation - and that's one of the sources of C++ performance. You are writing in a language that's much 'closer' to the hardware, and so the language features must contend with that in ways Java doesn't have to consider (it does that stuff under the hood).

    Despite the fact I tend to ramble on, there's not enough space to really answer your inquiry thoroughly - the answer touches on a number of points. I could simply tell you to use the STL Vector - and that's good advice, but it will leave you to discover how and when to use arrays effectively. It will take time, but frankly, it's worth it if you're going to make applications or other targets for which C++ is better suited.
    If my post was interesting or helpful, perhaps you would consider clicking the 'rate this post' to let me know (middle icon of the group in the upper right of the post).

  6. #6
    Join Date
    Apr 1999
    Posts
    27,449

    Re: Java to C++

    Quote Originally Posted by JVene View Post
    Yet, I must agree with potatoCode's basic point with this observation. Many Java programmers start learning C++, then after some time begin to complain about the language
    Many Java programmers don't even attempt to take the time to learn C++ properly before using it. Instead, they immediately attempt to write intermediate/advanced C++ programs, since the syntax is similar to Java.

    What ends up happening is that the C++ programs written by such programmmers are either wrong, buggy (i.e. full of memory leaks), or maybe work, but the code looks absolutely ridiculous (to a C++ programmer). For example, unnecessary calls to "new", attempting to write their own "Integer", "Double", and "Char" objects, etc. Check the many threads here where Java programmers have turned relatively simple C++ programs into convoluted messes due to trying to leverage what they learned in Java.

    Regards,

    Paul McKenzie

  7. #7
    Join Date
    Apr 2007
    Location
    Mars NASA Station
    Posts
    1,436

    Re: Java to C++

    In addition to that, follow the languages philosophy is often good approach.
    Thanks for your help.

  8. #8
    Join Date
    Jul 2002
    Location
    Portsmouth. United Kingdom
    Posts
    2,727

    Re: Java to C++

    I'd recommend http://www.cppreference.com/wiki/ as an easy to read resource for STL containers and algorithms.

    For more advanced information, go to http://www.sgi.com/tech/stl/
    "It doesn't matter how beautiful your theory is, it doesn't matter how smart you are. If it doesn't agree with experiment, it's wrong."
    Richard P. Feynman

  9. #9
    Join Date
    May 2009
    Posts
    28

    Re: Java to C++

    Thank you all for your comments.

    To summarize, yes, I m initially complaining at the very low level of C++ compared to Java, especially so when we have to deal with arrays, constructors, destructors et al. In addition, I m also working on a really complex project (dont have to code from start), so I have to literally Google for help quite often. That wasnt very productive. Example: I saw a strange code in the constructor and had no clue what it was. Unless I knew the right term for it ("constructor initializer list") I could not search for help and understand it.

    To add to my woes, there are are #'s and ifdefs/ifndefs etc.

    Its not just C++ learning curve, its also the makefiles and MSDEV environment that slows me down (i used Eclipse and Ant for Java)

    Thus, I learnt it the hard way that I must first systematically learn the key conceptual difference, esp. the terminologies associated with C++ before I can turn to google. Hence the need for a good book.

    Anyway, I foresee an uphill task, but am confident of negotiating it with enriching discussions on this forum. Thanks again for your continued patience and help.

    SG
    PS: I hope that my list of woes was reminiscent of your initial days of C++ programming. :-)

  10. #10
    Lindley is offline Elite Member Power Poster
    Join Date
    Oct 2007
    Location
    Seattle, WA
    Posts
    10,895

    Re: Java to C++

    It can be particularly difficult if you have to deal with code that's a mix of C and C++ styles. C is *really* low-level, while C++ doesn't have to be if you don't want to write it that way.

    While constructors/destructors usually correspond to memory management for an object, in some cases they can be used similarly to the Java try/finally construct: You ensure something happens before the scope exits, exception or no, by placing it in a destructor and constructing an object of that type on the stack.

  11. #11
    Join Date
    Apr 2004
    Posts
    102

    Re: Java to C++

    Here's a couple quick examples to illustrate some differences between C++ and Java that might help you with your initial questions. I'll use Java classes, and C++ structs for the examples, for clarity. I'll assume ints, pointers, and object references are 4-bytes in all cases. (My apologies if my Java syntax isn't perfect...I'm rusty)

    Java:
    Code:
    public class SomeClassA
    {
    	public int a,b,c;
    };
    
    public class SomeClassB
    {
    	public int d,e,f;
    	public someClassA objectG;
    };
    
    ...
    
    public void someMethod()
    {
    	SomeClassA object1; //allocates 4 bytes on the stack
    
    	SomeClassB object2, object3;
    		//allocates 2*4 bytes == 8 bytes on the stack
    
    	object1 = new SomeClassA(1,2,3);
    		//allocates 12 bytes in the heap, assigns the
    		//memory address to object1, if object1 goes
    		//out of scope, the garbage collector takes care
    		//of it later.
    	object2 = new SomeClassB(7,8,9,object1);
    		//allocates 16 bytes in the heap, assigns the
    		//memory address to object2, if object1 goes
    		//out of scope, the garbage collector takes care
    		//of it later.
    		//object2.objectG is assigned the same memory location
    		//in the heap as object1
    
    	object3 = new SomeClassB(4,5,6);
    		//allocates 16 bytes in the heap, assigns the
    		//memory address to object3, if object3 goes
    		//out of scope, the garbage collector takes care
    		//of it later.
    		//object3.objectG might remain unassigned
    		//or may be allocated (an addition 12 bytes on the heap)
    		//depending on how you build your constructor
    
    
    }
    Java notes:
    1) If the objects go out of scope AND are not being used in any scope, the garbage collector reclaims the memory. This uses a fair amount of processing overhead, which may not be an issue if your program is not already processor-intensive.
    2) You cannot change the memory addresses of the objects, except by direct assignment to a different object.

    C++:
    Code:
    struct someStructA
    {
    	int a,b,c;
    };
    
    struct someStructB
    {
    	int d,e,f;
    	struct someStructA structG;
    };
    
    struct someStructC
    {
    	int h,i,j;
    	struct someStructA* structPointerK;
    };
    
    ...
    
    void someFunction()
    {
    	struct someStructA struct1;
    		//allocates 12 bytes on the stack, contents are junk
    		//values until assigned separately.
    
    	struct someStructB struct2;
    		//allocates 24 bytes on the stack - a someStructB
    		//holds the entire structure of a someStructA in the
    		//same memory block.
    
    	struct someStructC struct3;
    		//allocates 16 bytes on the stack - the 3 ints plus
    		//a 4 byte pointer to a memory location that has not
    		//been allocated yet.
    
    	struct someStructA* structPointer4;
    		//allocates 4 bytes on the stack, pointer is unassigned
    		//and holds a junk value
    
    	structPointer4 = new structPointer();
    		//allocates 12 bytes on the heap, assigns that memory
    		//address to structPointer4, data members a,b,c remain
    		//uninitiallized to junk values
    
    	struct someStructA structArray5[4];
    		//allocates an array of 4 someStructA in one continuous
    		//block on the stack for 4*12 bytes == 48 bytes.
    		//To access an individual structure in an array use
    		//structArray5[0], structArray5[2].b, structArray5[3].a...
    
    	delete structPointer4;
    		//have to manually delete this out of the heap before
    		//it goes out of scope
    }
    C/C++ notes:
    1) A pointer is simply a 4-byte variable (on a 32-bit system) that holds a memory address, you can change the addresses manually, but this is not generally advised.
    2) You can allocate structs and classes directly on the stack! If they go out of scope, everything about it disappears, no garbage collector neccessary (no overhead).
    3) You can manually allocate structs and classes in the heap. CAREFUL! There is no garbage collector! If you allocate something on the heap using new you must manually de-allocate it using delete before the pointer goes out of scope and is lost, leaving the item clogging up memory on the heap (this is called a memory leak).
    4) C/C++ lets you make an array of any primitive (int, etc.), struct, or class. Unlike a Java ArrayList container object, C/C++ does not keep track of the length of the array. For example you can try to access structArray5[17] with no complaints from the compiler, even though your last element was #3. (A Standard Temple Library std::vector object is very similar to ArrayList).
    5) structArray5 without any brackets is treated as a pointer. Don't do this unless you really intend it.


    I could keep going with examples, but I this is all the time I have for now.

  12. #12
    Join Date
    Apr 2007
    Location
    Mars NASA Station
    Posts
    1,436

    Re: Java to C++

    You need to grasp the basic of C++ before try to code it.

    For instance,

    Code:
    class widget;
    
    widget a();
    The object declaration statement does not declare a widget object.
    Thanks for your help.

  13. #13
    Join Date
    Jul 2002
    Location
    Portsmouth. United Kingdom
    Posts
    2,727

    Re: Java to C++

    Quote Originally Posted by sgiri1981 View Post
    , I m initially complaining at the very low level of C++ compared to Java, especially so when we have to deal with arrays, constructors, destructors et al.
    As Lindley says, it doesn't have to be low level if you don't want it to be. That's the great attraction of C++; it can be either/both. Learn and take full advantage of the STL containers and algorithms; they will make a lot of the 'C' like low level stuff unnecessary.
    As you appear to be coding for a pre-existing project, you may find that there are areas that are not very 'C++' like, where previous coders have not used the full capabilities of C++.

    I'm surprised that you have to deal with make files. I use the MSDEV environment (Visual Studio 2008) and I've never had to do anything remotely like editing a makefile. I add files to the project tree and hit the 'Build' button!
    "It doesn't matter how beautiful your theory is, it doesn't matter how smart you are. If it doesn't agree with experiment, it's wrong."
    Richard P. Feynman

  14. #14
    Join Date
    Oct 2000
    Location
    London, England
    Posts
    4,773

    Re: Java to C++

    What you must pick up in C++ that is not there in Java is having to manage resources by use of automated destructors.

    C++ does not have memory garbage collection the way Java has it but does have the automatic destructor and advanced C++ programmers use these to do their garbage collection for them.

    You will not have to do all this management yourself because you should use both standard and open-source libraries available to you that already provide a lot of the support for this, for example you will almost certainly want to use shared_ptr at some point, either in the boost or tr1 namespace (namespace is similar to package in Java).

    In Java anything other than a primitive type must be created with new at all times. In C++ there are 3 ways a variable gets initialised:

    1. auto variables, which are kept on the stack and are destroyed at the end of the block
    2. heap-based variables allocated with new and require an explicit delete
    3. class members (not pointers) which are destroyed just after the class that holds them.

    Ignoring the complex "placement new" for now, the destructor of these objects gets called at the same the objects are destroyed.

    You also need to beware that objects can be copied and what implications that has, particularly if they share pointers.

    There is one other concept in C++ different from Java and that is const. You should learn to use that too.

  15. #15
    Lindley is offline Elite Member Power Poster
    Join Date
    Oct 2007
    Location
    Seattle, WA
    Posts
    10,895

    Re: Java to C++

    Another thing Java doesn't have is signed vs unsigned integers. There are a few gotchas there to watch out for, like the fact that -1 >= any unsigned value...

Page 1 of 3 123 LastLast

Posting Permissions

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





Click Here to Expand Forum to Full Width

Featured