Where is the definition of a class stored in memory as opposed to the instance? - oop

This question is merely out of interest and trying to understand something about memory management in object-oriented languages. It is not specific to one language, but I just want to understand as a general principle.
What I want to know is how the definition of an object reference is stored compared to the instance of that reference.
When you define and object in OO source code, e.g. in Java, without instantiating it:
String s;
How does this get stored? How does the memory usage of this definition differ from when the object is actually instantiated:
s = new String("abc");
? Is there a general principle that applies to all OO languages in terms of how memory is allocated or do different language implementers use different techniques for allocating memory?

Normaly when we declare a refrence like String s; it is created as a normal variable just like int , float but this type of variable hold the memory address ( it similar concept as pointers in C language) but when we use s = new String("abc");, it creates an object in heap and assign that address to the reference variable s.

In Java byte code, all Objects are stored as Objects. Explicit type-checking is added when needed. So for example this Java function
public Integer getValue(Object number){
int i = ((Number) number).toInt();
return new Integer(i);
}
is translated to a bytecode like this:
(accepts java.lang.Object, returns java.lang.Integer)
-read the first argument as an Object
-if the value is not a Number, raise an exception
-call the virtual method toInt(java.lang.Integer) of the value
and remember the int result
-use the value as an int argument
-instantiate a new java.lang.Integer
-call the constructor(int) of java.lang.Integer on the new number,
getting an Object back
[since the declared return value of Number.toInt is the same
as the return value of our function, no type checking is needed]
-return the value
So, types of unused variables get stripped out by the compiler. Types of public and protected fields are stored with its class.
The runtime type of an Object is stored with the object. In C++, it is a pointer to the Virtual Method Table. In Java, it is as a 16-bit index into the table of all loaded classes.
The Java class file stores an index of all dependent classes in a similar table. Only the class names are stored here. All field descriptions then point to this table.
So, when you write String s = new String("abc") (or even String s = "abc"), your class stores:
it is dependent on the class java.lang.String in the table of dependencies
"abc" in the table of String literals
your method loading a String literal by ID
(in the first case) your method calling a constructor of its first dependent class (String) with the first dependent class (String) as an argument.
the compiler can prove storing the new String in a String variable is safe, so it skips the type checking.
A class can be loaded as soon as it is referenced, or as late as its first use (in which case it is refered to by its depending class and ID within the class). I think the latter is always the case nowadays.
When a class is loaded:
-its class loader is asked to retreive the class by its name.
-(in the case of the system loader) the class loader looks
for the corresponding file in the program JAR, in the system library
and in all libraries referenced.
-the byte stream is then decoded into a structure in memory
-(in the case of early loading) all dependent classes are loaded recursively
if not already loaded
-it is stored in the class table
-(in the case of late loading) its static initialiser is run
(possibly loading more classes in the process).
In C++, none of the class loading takes place, as all user classes and most libraries are stored in the program as a mere virtual method table and the corresponding method. All of the system functions (not classes) can still be stored in a DLL (in case of Windows) or a similar file and loaded by the library at runtime. If a type checking is implied by an explicit type-cast, it is performed on the virtual method table. Also note that C++ did not have a type checking mechanism for a while.

Related

Can I have a string object store its data within the structure?

I'm looking for a quick way to serialize custom structures consisting of basic value types and strings.
Using C++CLI to pin the pointer of the structure instance and destination array and then memcpy the data over is working quite well for all the value types. However, if I include any reference types such as string then all I get is the reference address.
Expected as much since otherwise it would be impossible for the structure to have a fixed.. structure. I figured that maybe, if I make the string fixed size, it might place it inside the structure though. Adding < VBFixedString(256) > to the string declaration did not achieve that.
Is there anything else that would place the actual data inside the structure?
Pinning a managed object and memcpy-ing the content will never give you what you want. Any managed object, be it String, a character array, or anything else will show up as a reference, and you'll just get a memory location.
If I read between the lines, it sounds like you need to call some C or C++ (not C++/CLI) code, and pass it a C struct that looks similar to this:
struct UnmanagedFoo
{
int a_number;
char a_string[256];
};
If that's the case, then I'd solve this by setting up the automatic marshaling to handle this for you. Here's how you'd define that struct so that it marshals properly. (I'm using C# syntax here, but it should be an easy conversion to VB.net syntax.)
[StructLayout(LayoutKind.Sequential, CharSet=CharSet.Ansi)]
public struct ManagedFoo
{
public int a_number;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst=256)]
public string a_string;
}
Explanation:
StructLayout(LayoutKind.Sequential) specifies that the fields should be in the declared order. The default LayoutKind, Auto, allows the fields to be re-ordered if the compiler wants.
CharSet=CharSet.Ansi specifies the type of strings to marshal. You can specify CharSet.Ansi to get char strings on the C++ side, or CharSet.Unicode to get wchar_t strings in C++.
MarshalAs(UnmanagedType.ByValTStr) specifies a string inline to the struct, which is what you were asking about. There are several other string types, with different semantics, see the UnmanagedType page on MSDN for descriptions.
SizeConst=256 specifies the size of the character array. Note that this specifies the number of characters (or when doing arrays, number of array elements), not the number of bytes.
Now, these marshal attributes are an instruction to the built-in marshaler in .Net, which you can call directly from your VB.Net code. To use it, call Marshal.StructureToPtr to go from the .Net object to unmanaged memory, and Marshal.PtrToStructure to go from unmanaged memory to a .Net object. MSDN has some good examples of calling those two methods, take a look at the linked pages.
Wait, what about C++/CLI? Yes, you could use C++/CLI to marshal from the .Net object to a C struct. If your structs get too complex to represent with the MarshalAs attribute, it's highly appropriate to do that. In that case, here's what you do: Declare your .Net struct like I listed above, without the MarshalAs or StructLayout. Also declare the C struct, plain and ordinary, also as listed above. When you need to switch from one to the other, copy things field by field, not a big memcpy. Yes, all the fields that are basic types (integers, doubles, etc.) will be a repetitive output.a_number = input.a_number, but that's the proper way to do it.

Why do we need a constructor in OOP?

I am new to OOP. I am still in a learning phase.
Why do we need constructors, When we can initialize the values of the properties (variables) by writing a "Initialize function"?
Basically why do we write a constructor when we can achieve the same results even by writing a function for initializing the variables?
The constructor IS the "Initialize function"
Rather than calling two functions
object = new Class;
object.initialize();
You just call
object = new Class();
The logic inside the constructor can be identical to the logic inside the initialize function, but it's much tidier and avoids you naming your function initialize(), me naming mine initialize_variables(), and someone else naming theirs init_vars()... consistency is useful.
If your constructor is very large, you may still wish to split variable initialisation into a separate function and calling that function from your constructor, but that's a specific exception to the scenario.
So answer is simple
Why do we write Constructor?
Because in C you can write,
int i;
if write like this In above case data type and variable defines if you define like this memory allocated for i variable.So simple here we define class name and variable name(object name) we can create memory allocated for class name.
Example
myClass objectName;
But in C++ new keyword is used for dynamic memory allocation, so this dynamic memory which we can allocate to our class but here my example myClass is our class and we want to allocate to dynamic memory allocated.
So
myClass objectName = new myClass();
and simply constructor is memory allocation for class variable is called the constructor.`
the role of the constructor is to initialize the variables/values.it is the "initialization function".The only reason i find on why we use a constructor instead of a normal function to initialize the variables is to stop different people from using different function names and avoid ambiguity and it is much more easier to use a constructor which is instantiated automatically as soon as the class is run,instead of having to write a separate code for instantiation.this may seem small and like something that doesn't require much work,but only for a very small program,for larger ones the struggle is real.
It is usual to put mandatory things into the constructor and optional ones into the Initialise function.
For example, consider an amplifier that requires a power source so that would be supplied to its constructor. Logically, you may want to turn it on and set its power level but one could argue that you might not want to do that until later. In pseudo-code:
class Amplifier
{
public Amplifier(PowerSource powerSource)
{
// create amplifier...
}
public int PowerLevel;
public void Initialise()
{
// turn on...
}
}
The example, above, is rather puerile but it illustrates the concepts at play. It is always an issue of design, however, and opinions do vary.
Some classes of object, however, will have to perform obvious set-up operations during their construction phase. In these cases, the requirement to have a constructor is very easy to understand. For example, if your object might require a variable amount of memory, the constructor would be a logical place to allocate it and the destructor or finaliser would be a logical place to free it up again.
Even if you don't use constructor it will call implicitly by your language translator whenever you create object.Why?
The reason is that it is used for object initialization means the variable(instance) which we declare inside our class get initialized to their default value.
class Person {
//Class have two parts
//1.Data(instance variable)
//2.Methods(Sub-routine)
String name;
int age;
}
public class Stack{
public static void main(String[] args){
Person person1 = new Person();
System.out.println("Name: "+person1.name);
System.out.println("Age: " + person1.age);
}
}
Output- Name: null
Age: 0
"null" and "0" are default values which are impicitly set by default constructor.
When we initialize a class by creating an instance or object the constructor is called automatically. This is very helpful when we need a huge amount of code to be executed every time we create an object.
The best use of constructor can be seen when we create a " graphical user interface". While building a GUI for an application we need to separate the code for designing the GUI and the business logic of the application. In such a case we can write the code for designing GUI, in a constructor and business logic in respective methods. This make the code tidy and neat too.
Also when an object is created the global variables can be initialized to their default values using constructor. If we don't initialize the global variables, then the compiler will do it implicitly by using the default constructor.
So constructor is a very wise concept which appears to be an idiosyncrasy at first but as you code further and more and more you will realize it's importance.
Because constructors are exactly for that: to avoid using an "initialize function"
Plus you can have have as many constructors as you want: you juste feed them some parameters, depending how you want to inialize your object.
Constructor is a special member function which has same name as class name and called whenever object of that class is created. They are used to initialize data field in object.
Constructor has following properties:
It has same name as class name.
It is called whenever object of a class is created.
It does not have return type not even void.
It can have parameters.
Constructor can be overloaded.
Default constructor is automatically created when compiler does not find any constructor in a class.
Parameterized constructor can call default constructor using this() method.
A constructor can be static for static data field initialization.
It is not implicitly inherited.
For More Info
https://en.wikipedia.org/wiki/Constructor_(object-oriented_programming)

Should static reference type variable be avoided? [duplicate]

This question already has answers here:
Are static local variables bad practice?
(2 answers)
Closed 8 years ago.
Consider the following functionally two code snippets in a single-threaded environment. Assuming there are no other methods in Foo I believe these are functionally identical.
Class Foo
Private _Bar As Bar
Public ReadOnly Property GetBar As Bar
Get
If IsNothing(_Bar) Then
_Bar = New Bar
End If
Return _Bar
End Get
End Property
End Class
And
Class Foo
Public ReadOnly Property GetBar2 As Bar
Get
Static _Bar As New Bar
Return _Bar
End Get
End Property
End Class
Today I was challenged on code following the 2nd method because "the New will be called each time". I already know that is false, but the primary objection was with regards to the use of Static. I found several references to Static variables indicating that they may be dangerous, but they were all talking about Java. However, I was not able to find any good explanations as to why.
How are these two methods different? Is the 2nd method dangerous? If so, why?
Static in VB.Net is not that same as static in Java, C#, C, or C++. VB.Net's analog to that construct is Shared. The documentation on the Static keyword is here:
http://msdn.microsoft.com/en-us/library/z2cty7t8.aspx
In particular, I'd like to point out this snippet:
Behavior
When you declare a static variable in a Shared procedure, only one copy of the static variable is available for the whole application. You call a Shared procedure by using the class name, not a variable that points to an instance of the class.
When you declare a static variable in a procedure that isn't Shared, only one copy of the variable is available for each instance of the class. You call a non-shared procedure by using a variable that points to a specific instance of the class.
It's likely the objection comes from believing that Static always behaves like the first paragraph, even in instance methods, when we can see here that it's clearly documented that this is not the case.
Instead, Static allows you to declare a variable whose lifetime-scope is that of the class instance, but whose access-scope is limited to a single method. It's a way to narrow the potential scope of a variable, and therefore is a good thing. Additionally, variables declared as Static are rewritten by the compiler to be protected via the Monitor class (at least for the Shared version), giving them a measure of thread-safety. In other words, a variable declared as Static is more likely to have any needed locking done verses a similar class-scoped variable.
In this particular case, though, I fail to see the point. You don't really gain anything beyond an auto-implemented property like this:
Public ReadOnly Property GetBar2 As New Bar()
This probably is confusing the VB.net concepts of Static and Shared because some languages use the keyword Static to mean what VB uses Shared for: a variable/field/property/method that is shared or common to all instances of a class.
But Static doesn't mean that in VB. Instead it means a routine-local variable that persists beyond the invocation of the routine (i.e., its lifetime is object-scoped rather than routine invocation-scoped).
REF: http://msdn.microsoft.com/en-us/library/z2cty7t8.aspx
So in VB, Static means "routine-scoped visibility, object-scoped lifetime".
Whereas Shared means "class-scoped visibilty, class/program-scoped lifetime".
I would avoid the second approach if for no other reason than the fact that C and C# have a static keyword whose meaning is totally different from that of the VB.NET Static keyword. I generally dislike language features which look like features of other languages but aren't. If it's necessary to use a language feature despite its unfortunate resemblance to the other language's feature, I'll use it, but the VB.NET static keyword doesn't really add much here. Effectively, it asks the compiler to make the variable Private field, give it an arbitrary name which differs from that of any other field, and replace all references to the variable's given name within the method with references to the invented name.
Conceptually, use of such "localized" fields may be regarded as dubious because while one may expect that a field will only need to be used within one method, that may turn out not to be true. I wouldn't worry too much about that issue in vb.net, however, because a Static variable may easily be turned into an ordinary private field if the need arises. If when that need does arise a field exists with the same name, one may easily rename the Static variable before moving it.

What is the difference between an Instance and an Object?

What is the difference between an Instance and an Object?
Is there a difference or not?
The Instance and Object are from Object Oriented Programming.
For some programming languages like Java, C++, and Smalltalk, it is important to describe and understand code. In other languages that used in Structured Programming, this concept doesn't exist.
This is a view from Structural Programming. There's no real significant difference that should consume too much of your time. There might be some fancy language that some people might take up a lot of spaces to write about, but at the end of the day, as far as a coder, developer, programmer, architect, is concerned, an instance of a class and an object mean the same thing and can often be used interchangeably. I have never met anyone in my career that would be picky and spend a half-hour trying to point out the differences because there's really none. Time can be better spent on other development efforts.
UPDATE With regards to Swift, this is what Apple who invented Swift prefers :
An instance of a class is traditionally known as an object. However,
Swift classes and structures are much closer in functionality than in
other languages, and much of this chapter describes functionality that
can apply to instances of either a class or a structure type. Because
of this, the more general term instance is used.
Excellent question.
I'll explain it in the simplest way possible:
Say you have 5 apples in your basket. Each of those apples is an object of type Apple, which has some characteristics (i.e. big, round, grows on trees).
In programming terms, you can have a class called Apple, which has variables size:big, shape:round, habitat:grows on trees. To have 5 apples in your basket, you need to instantiate 5 apples. Apple apple1, Apple apple2, Apple apple3 etc....
Alternatively: Objects are the definitions of something, instances are the physical things.
Does this make sense?
Instance: instance means just creating a reference(copy).
object: means when memory location is associated with the object (is a run-time entity of the class) by using the new operator.
In simple words, Instance refers to the copy of the object at a particular time whereas object refers to the memory address of the class.
Object:
It is a generice term basically it is a Software bundle that has state(variables) and behaviour(methods)
Class:
A blue print(template) for an object
instance-it's a unique object thing for example you create a object two times what does that mean is yo have created two instances
Let me give an example
Class student()
{
private string firstName;
public student(string fname)
{
firstName=fname;
}
Public string GetFirstName()
{
return firstName;
}
}
Object example:
Student s1=new student("Martin");
Student s2=new student("Kumar");
The s1,s2 are having object of class Student
Instance:
s1 and s2 are instances of object student
the two are unique.
it can be called as reference also.
basically the s1 and s2 are variables that are assigned an object
Objects and instances are mostly same; but there is a very small difference.
If Car is a class, 3 Cars are 3 different objects. All of these objects are instances. So these 3 cars are objects from instances of the Car class.
But the word "instance" can mean "structure instance" also. But object is only for classes.
All of the objects are instances.
Not all of the instances must be objects. Instances may be "structure instances" or "objects".
I hope this makes the difference clear to you.
Let's say you're building some chairs.
The diagram that shows how to build a chair and put it together corresponds to a software class.
Let's say you build five chairs according to the pattern in that diagram. Likewise, you could construct five software objects according to the pattern in a class.
Each chair has a unique number burned into the bottom of the seat to identify each specific chair. Chair 3 is one instance of a chair pattern. Likewise, memory location 3 can contain one instance of a software pattern.
So, an instance (chair 3) is a single unique, specific manifestation of a chair pattern.
Quick and Simple Answer
Class : a specification, blueprint for an object...
Object : physical presence of the class in memory...
Instance : a unique copy of the object (same structure, different data)...
An object is a construct, something static that has certain features and traits, such as properties and methods, it can be anything (a string, a usercontrol, etc)
An instance is a unique copy of that object that you can use and do things with.
Imagine a product like a computer.
THE xw6400 workstation is an object
YOUR xw6400 workstation, (or YOUR WIFE's xw6400 workstation) is an instance of the xw6400 workstation object
Java is an object-oriented programming language (OOP). This means, that everything in Java, except of the primitive types is an object.
Now, Java objects are similar to real-world objects. For example we can create a car object in Java, which will have properties like current speed and color; and behavior like: accelerate and park.
That's Object.
Instance, on the other side, is a uniquely initialized copy of that object that looks like Car car = new Car().
Check it out to learn more about Java classes and object
Once you instantiate a class (using new), that instantiated thing becomes an object. An object is something that can adhere to encapsulation, polymorphism, abstraction principles of object oriented programming and the real thing a program interacts with to consume the instance members defined in class. Object contains instance members (non-static members).
Thus instance of a class is an object. The word ‘instance’ is used when you are referring to the origin from where it born, it's more clearer if you say ‘instance of a class’ compared to ‘object of a class’ (although the latter can be used to).
Can also read the 'Inner classes' section of this java document on nested classes - https://docs.oracle.com/javase/tutorial/java/javaOO/nested.html
I can't believe, except for one guy no one has used the code to explain this, let me give it a shot too!
// Design Class
class HumanClass {
var name:String
init(name:String) {
self.name = name
}
}
var humanClassObject1 = HumanClass(name: "Rehan")
Now the left side i.e: "humanClassObject1" is the object and the right side i.e: HumanClass(name: "Rehan") is the instance of this object.
var humanClassObject2 = HumanClass(name: "Ahmad") // again object on left and it's instance on the right.
So basically, instance contains the specific values for that object and objects contains the memory location (at run-time).
Remember the famous statement "object reference not set to an instance of an object", this means that non-initialised objects don't have any instance.
In some programming languages like swift the compiler will not allow you to even design a class that don't have any way to initialise all it's members (variable eg: name, age e.t.c), but in some language you are allowed to do this:
// Design Class
class HumanClass {
var name:String // See we don't have any way to initialise name property.
}
And the error will only be shown at run time when you try to do something like this:
var myClass = HumanClass()
print(myClass.name) // will give, object reference not set to an instance of the object.
This error indicates that, the specific values (for variables\property) is the "INSTANCE" as i tried to explain this above!
And the object i.e: "myClass" contains the memory location (at run-time).
This answer may be seen as trite, but worrying about the differences between an instance and object is already trite city.
I think its best depicted in javascript:
let obj= {"poo":1}
// "obj" is an object
verses
Class Trash {
constructor(){this.poo = 1;}
}
let i = new Trash();
// "i" is an instance
When a variable is declared of a custom type (class), only a reference is created, which is called an object. At this stage, no memory is allocated to this object. It acts just as a pointer (to the location where the object will be stored in future). This process is called 'Declaration'.
Employee e; // e is an object
On the other hand, when a variable of custom type is declared using the new operator, which allocates memory in heap to this object and returns the reference to the allocated memory. This object which is now termed as instance. This process is called 'Instantiation'.
Employee e = new Employee(); // e is an instance
However, in some languages such as Java, an object is equivalent to an instance, as evident from the line written in Oracle's documentation on Java:
Note: The phrase "instantiating a class" means the same thing as "creating an object." When you create an object, you are creating an "instance" of a class, therefore "instantiating" a class.
An instance is a specific representation of an object. An object is a generic thing while an instance is a single object that has been created in memory. Usually an instance will have values assigned to it's properties that differentiates it from other instances of the type of object.
If we see the Definition of Object and Instance object -
Memory allocated for the member of class at run time is called object or object is the instance of Class.
Let us see the Definition of instance -
Memory allocated For Any at run time is called as instance variable.
Now understand the meaning of any run time memory allocation happen in C also through Malloc, Calloc, Realloc such:
struct p
{
}
p *t1
t1=(p) malloc(sizeof(p))
So here also we are allocating run time memory allocation but here we call as instance so t1 is instance here we can not say t1 as object so Every object is the instance of Class but every Instance is not Object.
Object - An instance of a class that has its own state and access to all of the behaviour defined by its class.
Instance - Reference to an memory area for that particular class.
Class : A class is a blue print.
Object : It is the copy of the class.
Instance : Its a variable which is used to hold memory address of the object.
A very basic analytical example
Class House --> Blueprint of the house. But you can't live in the blue print. You need a physical House which is the instance of the class to live in. i.e., actual address of the object is instance. Instances represent objects.
There are 3 things you need to understand : Class , Object and Instance.
Class : Class is the blueprint code from which you will create an Object(s)
Object : When memory is allocated to the data entity (created from blueprint class) , that data entity or reference to it is called Object
Instance : When data is filled in an Object , it becomes an instance of that Object. It can also be called a state of that Object.
Example : In context with C# (objects are reference type here)
Lets say we have a class like this (This is your blueprint code)
public class Animal
{
//some fields and methods
}
We create an object like this
Animal a = new Animal();
Animal b = a;
Animal c = a;
Animal d = b;
So here is the question : How many objects and instances are here ?
Answer : There is only 1 object but 4 instances.
Why ?
In first line (Animal a = new Animal();),we created an Object from class Animal with new Operator. That Object is somewhere on your RAM. And the reference to that Object is in "a".
We have 1 object and 1 instance at this time.
Now in next line, we assign b with a. Here Object is not copied but the reference of object from "a" is stored in "b" too. Thus , we have 2 instances , "a and b".
This goes on and we only copy reference of same object located at some memory.
Finally , we have 4 instances "a,b,c,d" of a single object that was created with new Operator.
(Read how reference type works in C# for more. I hope you understand my language)
each object said to be an instance of its class but each instance of the class has its own value for each attributes
intances shares the attribute name and operation with their intances of class but an object contains an implicit reference to his on class
I can't believe this could be hard to be explain but it actually easier than all the answers I read. It just simple like this.
Firstly, you need understand the definition:
Instance is a **unique copy-product of an Object.
**unique - have different characteristic but share the same class compare to object
Object is a name that been used to keep the Class information (i.e
method)
Let say, there is an toy_1 as an object.
There is also toy_2 as an object ----> which ALSO an INSTANCE to toy_1.
At the same time, toy_1 also an INSTANCE to toy_2. (remember again INSTANCE is a COPY-PRODUCT)
That is why most of the answer I found said it is INTERCHANGABLE. Thank you.
I think if we consider other approaches than OOP (mainly by assuming the term Class hasn't always been used, as it's the case for many C projects, which still applied the concept of Objects), following definitions would make the most sense:
A Class defines an interface that objects adhere to.
An Object is an aggregate of different fields. (It doesn't have to "physically" exist, but it can).
All Objects of the same Class can be used in the same way, defined by the Class.
An Instance is a unique realization of an Object.
As many OOP languages use static typing, the Object description is usually part of the Class already. As such, when talking about an Object in C/C++, what usually is meant is the Instance of an Object.
In languages that do not have static typing (such as JavaScript), Objects can have different fields, while still sharing the same Class.
Regarding the difference between an object and an instance, I do not think there is any consensus.
It looks to me like people change it pretty much interchangeably, in papers, blog posts, books or conversations.
As for me, the way I see it is, an object is a generic and alive entity in the memory, specified by the language it is used in. Just like the Object class in Java. We do not much care its type, or anything else associated with it, whether it is managed by a container or not.
An instance is an object but associated with a type, as in this method accepts Foo instances, or you can not put Animal instances in an instance of
a List of Vehicles.
objects for example have locks associated with them, not instances, whereas instances have methods. objects are garbage collected, not instances.
But as I said, this is only how I see it, and I do not think there is any organisation we can refer to for a standard definition between them and everyone will pretty much have their slightly different understanding / definitions (of course within limits).
An object is a generic thing, for example, take a linear function in maths
ax+b is an object, While 3x+2 is an instance of that object
Object<<< Instance
General<<< Specific
There is nothing more to this
An object can be a class, say you have a class called basketball.
but you want to have multiple basketballs so in your code you create more than 1 basketball
say basketball1 and basketball2.
Then you run your application.
You now have 2 instances of the object basketball.
Object refers to class and instance refers to an object.In other words instance is a copy of an object with particular values in it.

ABAP create object

Below is a code snippet that is creating object.
Form userexit_save_document_prepare.
data: /bks/exitmanager type ref to /bks/exit_manager.
create object /bks/exitmanager
exporting main_prog = 'SAPMV45A'
exit_form = 'USEREXIT_SAVE_DOCUMENT_PREPARE'.
include /bks/exitman.
ENDFORM.
I got this from the documentation
For performance reasons, the parameters "main_prog" and "exit_form" should be filled, in the case of userexits, which are performed very often like "user_field_modification" in "SAPMV45A" which is called for every single screen-field.
1) What happened exactly behind when create object /bks/exitmanager is called? memory allocated for the object etc?
2) Why for performance reasons the exporting parameters of create object needs to be filled?
I'm not 100% sure, but here is my best guess:
an object called /bks/exitmanager is constructed (which is an oject of the class /bks/exit_manager or more specific a reference/"pointer" to an object of this class) .. the required memory allocated etc., but also the "constructor" code is called (probably sets some instance variables as passed to the call).
If you're explicitly passing these parameters, they don't have to be "calculated" at run-time (e.g. by looking at the call stack). This should save some time, especially if it would have to be done quite often (as described in the documentation).
It would help to see what /bks/exit_manager actually is, and a brief explanation of what you are trying to accomplish.
Expanding on what IronGoofy wrote:
data: /bks/exitmanager type ref to /bks/exit_manager
This creates a reference pointer in the ABAP memory of your program, much like a field symbol. Also it must be already delared. If it is in the include, you need to move the include.
create object /bks/exitmanager
exporting main_prog = 'SAPMV45A'
exit_form = 'USEREXIT_SAVE_DOCUMENT_PREPARE'.
This creates an object instance based on the declared class, and assigns it to the referance pointer. It does this by calling the constructor method first.
Only by examing /bks/exit_manager will you find out exactly what you need to export.
It's impossible to tell what's going on and why the parameters should be passed without taking a look at the constructor of /BKS/EXIT_MANAGER. It's a common pattern though to keep a buffer of settings (think of a static hashed table with the key being the parameters and the value holding whatever is complicated and time-consuming to fetch). In this case, I would have expected a protected constructor that cannot be accessed directly, but only using a static factory method that uses a hashed table to keep the references of the exit handler itself - optimally using weak references...