java question

0 views
Skip to first unread message

Rajesh Inakota

unread,
Jul 6, 2011, 1:56:11 PM7/6/11
to freak...@googlegroups.com
How to make class to be created only on hash not on stack?

--
Regards,
Rajesh.I

Sridivakar Inakonda

unread,
Jul 6, 2011, 8:58:51 PM7/6/11
to Freak-Your-Mind [FYM]
In Java, memory for every Object gets allocated from heap not from
stack. Only reference to that object can exists on stack.

-Divakar.

Rajesh Inakota

unread,
Jul 6, 2011, 11:48:00 PM7/6/11
to freak...@googlegroups.com
Agreed divakar.

What if I want to do this with C++?
--
Regards,
Rajesh.I

Shyam Prakash Velupula

unread,
Jul 7, 2011, 12:26:24 AM7/7/11
to freak...@googlegroups.com
Make the ctor & dtor private. Define a public static method that construct the object on heap (just like factory method). Of course provide a public static method to destruct the same.

Thanks
Shyam Velupula
--
You are limited only by your imagination

Rajesh Inakota

unread,
Jul 8, 2011, 5:18:59 AM7/8/11
to freak...@googlegroups.com
what is the output of below code? what will it print?

class SimpleObj {
    int i;
}

public class PassObject {

    public static void passObject(SimpleObj from, SimpleObj to) {
        to = from;
    }

    public static void main(String[] args) {
        SimpleObj obj = new SimpleObj();
        SimpleObj  from = obj;
        SimpleObj to = null;
        
        passObject(from, to);
        System.out.println(to.i);
    }
}


--
Regards,
Rajesh.I

Sridivakar Inakonda

unread,
Jul 8, 2011, 8:07:52 PM7/8/11
to freak...@googlegroups.com
I guess, this should through nullpointer exception, because of

        System.out.println(to.i);

is accessing null object, passObject() is not changing value on this "to"  reference, it is changing value of reference on stack.

-Divakar.

Rajesh Inakota

unread,
Jul 9, 2011, 3:01:42 PM7/9/11
to freak...@googlegroups.com
yes.
--
Regards,
Rajesh.I

ashok Mudithanapalli

unread,
Jul 11, 2011, 2:30:58 AM7/11/11
to freak...@googlegroups.com
post more CPP questions.........:)
Reply all
Reply to author
Forward
0 new messages