-3

In java it is possible to write a code like

public class Print{
int n=10;
String path="C:\\file.txt";
}

Where does the memory for these data members are allocated before object creation ?? And i suppose we can't do the same in C++ !! Explain me with C++ and Java ...

Dinesh
  • 13
  • 6

3 Answers3

3

In Java, there is a class named Class, and there is one Class object for each class laoded into the runtime. Those Class objects contain amongst other things those data like the 10 and the "C:\file.txt" needed for initalization.

In C++11 you can do the same, (at least it looks the same and has the same semantics in a C++-ish way):

class Print
{
  int n = 10;
  std::string path = "C:\\file.txt";
};

In C++03 that is not possible, there you'd have to initialize the members in every constructor. How that is implemented in C++11 is something different to Java: unlike in Java, there are no Class objects in C++, there is no class loading at runtime. In C++11 this kind of member initializers are treated by the compiler as if you had written the initializers in every constructor by hand. Somewhere in the compiled program code you have the 10 and the "C:\file.txt", and each constructor's code contains a section where the two members of the to-be-constructed object get initialized with those values. That is, unless you explicitly initialize one or both of the members in the constructor, because that would override the default initializers.

Arne Mertz
  • 24,171
  • 3
  • 51
  • 90
0

In java no memory is allocated to the Object until the keyword 'new' is used or in case of strings assigning a value to it.

Poka Yoke
  • 373
  • 3
  • 8
  • 27
0

Neighter in Java nor in C++ you can't access variables n and path before you create an object of type Print. In what kind of memory an object will be created, in the same kind of memory would be created all it's fields.

In C++, when you create object like this

void foo() {
    Print obj;
}

it will be created in stack. And if you create an object like this

void foo() {
    Print * obj = new Print;
}

it will be created in heap.

In Java you can create only heap-allocated objects, so both object itself and it's fields will be placed into heap.

Pay an attention, that initializing class's fields in declaration allows only in C++11, not in C++03

borisbn
  • 4,988
  • 25
  • 42