Java Classes vs C++ Classes
In C++, when
we declare a variable whose type is a class, storage is
allocated for an object of that class, and the class's constructor
function is called to initialize that instance o f theclass. On the other hand,
in Javawhen we declare a variable whose type is a class, we
really declare apointer or reference to a class object;
no storage is allocated for the classobject, and no constructor function
is called unless we use the "new" keyword. This is elaborated with
the help of the following example:
Let us assume we have the following class:
class MyClass {
// class definition goes here
}
Let us first look at C++
MyClass m; // m is an object of type MyClass
// the constructor function is called to initialize M.
MyClass *pm; // pm is a pointer to an object of type MyClass
// no object exists yet, no constructor function has been called
pm = new MyClass; // now storage for an object of MyClass has been
// allocated and the constructor function has been called
Now the same thing in Java
MyClass m; // pm is a pointer to an object of type MyClass
// no object exists yet, no constructor function has been called
m = new MyClass(); // now storage for an object of MyClass has been
// allocated and the constructor function has been called. Note
// that you must use parentheses even when you are not
// passing any arguments to the constructor function
// Also note that there is a simple ‘.’ (dot) operator used to
// access members or send message. Java does not use -> operator.
Let us assume we have the following class:
class MyClass {
// class definition goes here
}
Let us first look at C++
MyClass m; // m is an object of type MyClass
// the constructor function is called to initialize M.
MyClass *pm; // pm is a pointer to an object of type MyClass
// no object exists yet, no constructor function has been called
pm = new MyClass; // now storage for an object of MyClass has been
// allocated and the constructor function has been called
Now the same thing in Java
MyClass m; // pm is a pointer to an object of type MyClass
// no object exists yet, no constructor function has been called
m = new MyClass(); // now storage for an object of MyClass has been
// allocated and the constructor function has been called. Note
// that you must use parentheses even when you are not
// passing any arguments to the constructor function
// Also note that there is a simple ‘.’ (dot) operator used to
// access members or send message. Java does not use -> operator.