firstly what do you guys feel of friend methods? how much do u use them within yur code. i got the feeling that as "friend"ly as they might be they broke the oops principle of encapsulation.
You are right about violating the principle of encapsulation. But I think it is a "controlled" violation. It's not like any class/method out there can claim to be your friend and access your privates. YOU decide who your friend is. I could even see this as a convenience feature. If you mess up in design and want someone in the outside world to see some data, but not everyone, make him a friend.
whats the difference between creating an instance using new vs without new
Without new, the instance is created on the stack and memory management is taken care by the compiler. With new, it's created on the c++ heap and you have to make sure and call delete.
new is supposed to be dynamic runtime allocation so are instances like stack a given a memory space just when the os creates the app
Yeah, I think that's what happens. But I'm not sure exactly how it works. If one of you could explain the process.
Also you have read stuff on OS right? Have you gone into details about what happens when an app is executed? Like what does the OS do? OS Loader, creating new process etc... Could you post about that? I have not done anything in OS, but am very interested in it.
also is there a heap and stack in c++. can i specify where i can create the instance. this is possible in c# right? code snippet please.
Yeah there's a heap and stack in c++... same with c# and java. In c++ classes can be created on the stack or the heap. In c# classes can ONLY be created on the heap and structs can be created ONLY on the stack. Structs in c# are NOT the same as structs in c++. Structs in c++ are the same as Classes but their default access level for members is public. Java has no structs, only classes and they can ONLY be created on the heap.
// C++
MyClass x; // object created on stack
MyClass x2 = new MyClass; // object created on heap
MyStruct y; // object created on stack
MyStruct y2 = new MyStruct; // object created on heap
// C#
MyClass x; // just declares x to be a reference to a MyClass object (initialized to null)
MyClass x2 = new MyClass(); // object created on heap
MyStruct y; // object created on stack (initialized to 0, by compiler)
MyStruct y2 = new MyStruct(); // object created on stack (default constructor called)
// Java
MyClass x; // just declares x to be a reference to a MyClass object (initialized to null)
MyClass x2 = new MyClass(); // object created on heap
does c# allow overloaded operators?
Yup. They have to be declared as static methods of the class...
public class MyClass
{
private int x;
public MyClass( int x )
{
this.x = x;
}
public static MyClass operator+( MyClass that )
{
return new MyClass( this.x + that.x );
}
}
No comments:
Post a Comment