In: Computer Science
(3) Briefly (in just a few words), describe the difference between
an instance and a class.
For better understanding of the concepts, We will first look on class and then an instance.
The Concepts are explained in C++ Language!
Class:
In Object Oriented Programming, Class is a Building block and it acts as a container contains set of variables and functions.
Syntax of a Class:
class class_name
{
Set of variables;
Set of functions;
}
Example:
class sum // class named 'sum; is created.
{
public:// Elements of the class can be accessed outside class.
int a,b,c;// the class 'sum' contains three variables 'a,b,c' of type integer.
a=10,b=5;// 'a' is assigned with value 10 and 'b' is assigned with value 5
void add()// function is created with name 'sum'
{
c=a+b;// value in the variables a and b are added ans the result is stores in variable c
cout<<c;// value in variable'c' is printed.
}
};// end of the class
An Instance :
An instance is otherwise called as Objects in Object Oriented Programming.
An object is an instance(copy) of a class. When the object is created, memory will be allocated to all the elements of a class.
In the above example, we have created a class called 'sum' , but no process will takes place in it.
We have to activate the class with the help of object.( An instance).
Syntax for cretating object:
class_name object_name;
Example:
sum obj; // Here 'obj' is the instance of the class 'sum'.
We can use the instance 'obj' to access the members of the class.
Syntax to access function of a class with object:
object_name.function_name();
Example:
obj.add();// Now, the instance(obj) of the class 'sum' will access the function 'add'.
So, the instance is using the copy of a class and necessary process will takes place.
Output:
15
Differences:
Class:
1. A class is a template.
2. A class does not allocate memory space to its element, when it is created.
3. You can declare class only once.
An instance(Object):
1. The object is an instance of a class.
2. Object allocates memory space for the class elements whenever they are created.
3. we can create more than one object for one class
Hope you find it useful!! Thnak you!!! Happy learning!!!