Monday, May 20, 2013

Moving From Java to C++


Moving From Java to C++


main function

C++

// free-floating function
int main( int argc, char* argv[])
{
    printf( "Hello, world" );
}

Java

// every function must be part of a class; the main function for a particular
// class file is invoked when java <class> is run (so you can have one
// main function per class--useful for writing unit tests for a class)
class HelloWorld
{
    public static void main(String args[])
    {
        System.out.println( "Hello, World" );
    }
}

Compiling

C++

    // compile as
    g++ foo.cc -o outfile
    // run with
    ./outfile
    

Java

    // compile classes in foo.java to <classname>.class
    javac foo.java 

    // run by invoking static main method in <classname>
    java <classname>
    

Comments

Same in both languages (// and /* */ both work)

Class declarations

Almost the same, but Java does not require a semicolon

C++

    class Bar {};
    

Java

    class Bar {}
    

Method declarations

Same, except that in Java, must always be part of a class, and may prefix with public/private/protected

C++: public, private, protected sections 

Constructors and destructors

Constructor has same syntax in both (name of the class), Java has no exact equivalent of the destructor (due to garbage collection mechanism) 

Static member functions and variables

Same as method declarations, but Java provides static initialization blocks to initialize static variables (instead of putting a definition in a source code file):
class Foo 
{
    static private int x;
    // static initialization block (for Java only) 
    { x = 5; }
}

Scoping static methods and namespaces

C++

If you have a class and wish to refer to a static method, you use the form Class::method.
class MyClass
{
    public:
    static doStuff();
};

// now it's used like this
MyClass::doStuff();

Java

All scoping in Java uses the . again, just like accessing fields of a class, so it's a bit more regular:
class MyClass
{
    public static doStuff()
    {
        // do stuff
    }
}

// now it's used like this
MyClass.doStuff();

Object declarations

C++

    // on the stack
    myClass x;
something like NULL pointer exception in java
    // or on the heap
    myClass* x = new myClass;
    

Java

    // always allocated on the heap (also, always need parens for constructor)
    myClass x = new myClass();
    

Accessing fields of objects

C++

If you're using a stack-based object, you access its fields with a dot:
myClass x;
x.my_field; // ok
But you use the arrow operator (->) to access fields of a class when working with a pointer (heap-based):
myClass* x = new MyClass();
x->my_field; // ok

Java

You always work with references (which are similar to pointers--see the next section), so you always use a dot:
myClass x = new MyClass();
x.my_field; // ok

References vs. pointers

C++

    // references are immutable, use pointers for more flexibility
    int bar = 7, qux = 6;
    int& foo = bar;
    

Java

    // references are mutable and store addresses only to objects; there are
    // no raw pointers
    myClass x;
    x.foo(); // error, x is a null ``pointer''

    // note that you always use . to access a field
    

Inheritance

C++

    class Foo : public Bar
    { ... };
mostly used: public inheritance 
private, protected inheritance are hardly ever used 

Java

    class Foo extends Bar
    { ... }
    

Protection levels (abstraction barriers)

C++

    public:
        void foo();
        void bar();
    

Java

    public void foo();
    public void bar();
    

Virtual functions

C++

    virtual int foo(); // or, non-virtually as simply int foo();


to be compatible to Java, I may put "virtual" to all the methods. 
    

Java

    // functions are VIRTUAL BY DEFAULT; use final to prevent overriding
    int foo(); // or, final int foo();


virtual function tutorial 
Here’s the above example with a virtual function:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Base
{
protected:
public:
    virtual const char* GetName() { return "Base"; }
};
class Derived: public Base
{
public:
    virtual const char* GetName() { return "Derived"; }
};
int main()
{
    Derived cDerived;
    Base &rBase = &cDerived; //upcasting 
    cout << "rBase is a " << rBase.GetName() << endl;
    return 0;
}
This example prints the result:
rBase is a Derived
Because rBase is a pointer to the Base portion of a Derived object, when rBase.GetName() is evaluated, it would normally resolve to Base::GetName(). However, Base::GetName() is virtual, which tells the program to go look and see if there are any more-derived versions of the function available. Because the Base object that rBase is pointing to is actually part of a Derived object, the program will check every inherited class between Base and Derived and use the most-derived version of the function that it finds. In this case, that is Derived::GetName()!
    

Abstract classes

C++

    // just need to include a pure virtual function
    class Bar { public: virtual void foo() = 0; };
    

Java

    // syntax allows you to be explicit!
    abstract class Bar { public abstract void foo(); }

    // or you might even want to specify an interface
    interface Bar { public void foo(); }

    // and later, have a class implement the interface:
    class Chocolate implements Bar
    {
        public void foo() { /* do something */ }
    }
    

Memory management

Roughly the same--new allocates, but no delete in Java since it has garbage collection.

NULL vs. null

C++

    // initialize pointer to NULL
    int *x = NULL;
    

Java

    // the compiler will catch the use of uninitialized references, but if you
    // need to initialize a reference so it's known to be invalid, assign null
    myClass x = null;
    

Booleans

Java is a bit more verbose: you must write boolean instead of merely bool.

C++

bool foo;

Java

boolean foo;

Constness

C++

    const int x = 7;
    

Java

    final int x = 7;
    

Throw Spec

First, Java enforce throw specs at compile time--you must document if your method can throw an exception

C++

int foo() throw (IOException)

Java

int foo() throws IOException

Arrays

C++

    int x[10];
    // or 
    int* x = new x[10];
    // use x, then reclaim memory
    delete[] x;
    

Java

    int[] x = new int[10];
    // use x, memory reclaimed by the garbage collector or returned to the
    // system at the end of the program's lifetime
    

Collections and Iteration

C++

Iterators are members of classes. The start of a range is <container>.begin(), and the end is <container>.end(). Advance using ++ operator, and access using *.
    vector myVec;
    for ( vector<int>::iterator itr = myVec.begin();
          itr != myVec.end();
          ++itr )
    {
        cout << *itr; //Pointer 
    }
    

Java

Iterator is just an interface. The start of the range is <collection>.iterator, and you check to see if you're at the end with itr.hasNext(). You get the next element using itr.next() (a combination of using ++ and * in C++).
    ArrayList myArrayList = new ArrayList();
    Iterator itr = myArrayList.iterator();
    while ( itr.hasNext() )
    {
        System.out.println( itr.next() );
    }

    // or, in Java 5
    ArrayList myArrayList = new ArrayList();
    for( Object o : myArrayList ) {
        System.out.println( o );
    }
    

No comments:

Post a Comment