1. In C++, everything is an object. Compare the following code segment (Foo is a class):
C++
Code:
int a;
char b;
Foo *c;
Java
Code:
int a;
char b;
Foo c;
In the C++ example, a, b, c are objects but, in Java, they are not objects. Therefore, in Java, you cannot make pointers point to a, b and c.
2. There are references in C++ but not in Java. For example, the following C++ code is not possible in Java:
Code:
void swap(int &a,int &b) {
int c=a;
a=b;
b=c;
}
3. C++ has pointer arithmetic but not in Java. For example, the following C++ code segment is not possible in Java:
Code:
int *p=new int[10];
int *q=p + 3;
4. (deleted)
5. In C++, you are free to allocate objects in the program image, in the heap or on the stack. In Java, you can only allocate objects in the heap and primitives and pointers on the stack. The following C++ code is not possible in Java. (Foo is a class)
Code:
class Blah {
public:
void method() {
Foo a; // a is allocated on the stack and is destructed automatically when a goes out of scope.
}
};
6. In C++, object are values. In Java, object are not values. Therefore, in combination of the fact that Java has no references, you cannot pass an object into a function or return an object, only their pointers can be passed around. In Java, you must also manually write a clone function to copy an object but in C++, a simple assignment copies an object. The following C++ code is not possible in Java.
Code:
class Foo {
};
void func(Foo x) {
}
int main() {
const Foo x;
}
7. In Java, objects cannot be made read-only (although pointer that points to the object can). See the above code for example.
8. In Java, there is no operator overloading. Therefore, it is impossible to write generics that applies to both primitives and objects. Here is a bubble sort algorithm written in C++, which is not possible in Java:
Code:
template <class T> void sort(T *begin, T *end) {
for(T* i=end; i > begin; --i) {
for(T* j=begin; j + 1 < i; ++j) {
if(j[1] < j) {
swap(j, j[1]);
}
}
}
}
9. In C++, there is full multiple inheritance. In Java, a class can implement more than one interface but can only extend one class. For example, the following is not possible in Java:
Code:
class BaseOne {
public:
void aa()=0;
void ab() {
// implemented
}
};
class BaseTwo {
public:
void xa()=0;
void xb() {
// implemented
}
};
class Derived: public BaseOne, BaseTwo {
};
Bookmarks