Class
In OOP, a class is a blueprint from which individual instances are created.
A class is a blueprint for creating objects (a particular data structure), providing initial values for state (member variables or attributes), and implementations of behavior (member functions or methods).
We define a class using the class keyword.
Classes are of reference types.
All the reference types are allocated on heap memory.
Example - #include <stdio.h>
-
-
class Test {
-
int x; // x is private
-
};
-
int main()
-
{
-
Test t;
-
t.x = 20; // compiler error because x is private
-
getchar();
-
return 0;
-
}
Structure
A struct is similar to a class in terms of definition and instance creation.
We define a struct using the struct keyword.
Structs are of value types.
All the value types are allocated on stack memory.
Classes can contain constructor or destructor.
Structure does not contain parameter less constructor or destructor, but can contain Parameterized constructor or static constructor.
Example - #include <stdio.h>
-
-
struct Test {
-
int x; // x is public
-
};
-
int main()
-
{
-
Test t;
-
t.x = 20; // works fine because x is public
-
getchar();
-
return 0;
-
}
-