Classes in C++
Class:-
- Class is a collection of a characteristics and a behaviors.
- Characteristics means data members defined in the class and behaviors means a member functions/methods which are defined in the class and this methods are applied on to the characteristics of the class.
e.g.
class demo
{
public:
int i,j;
void fun()
{
cout<<”Inside the fun of demo”;
cout<<i;
cout<<j;
}
};
- In the above example, demo is our class which contains two characteristics as I and j. and both are integers.
- Behaviors of the demo class is a function fun() which applied on the data types i and j.
- To use above class we have to create an instance of that class means we have to create an object of that class.
e.g.
demo d;
or
class demo d;
- In the above syntax, we create an object of the class demo named as d.
- In the C++, writing a keyword class, struct and union while creating an object is optional but in C it is Compulsory.
Struct demo
{
int i,j;
};
Struct demo d; // This is the syntax which is used in C.
Demo d; // This is the syntax which is used in C++.
Memory allocation for the class:-
Class demo
{
public:
int i,j,k;
float f;
int fun()
{
cout<<”Inside the fun of demo”;
}
int gun()
{
cout<<”Inside the gun of demo”;
}
};
int main()
{
cout<<sizeof(demo); // 16
demo d;
cout<<sizeof(d); // 16
return 0;
}
- In this example, memory allocated for our class is 16 bytes, because, this class contains 3 integers and 1 float data type.
- This class also contains two functions namely as fun() and gun().
- When we create an multiple objects of same class then memory allocated for each and every object is 16 bytes.
- But there is no memory allocation for functions of a class, because, function definitions do not vary across the object but the data members of an objects vary across the object.
- Important things about the memory allocation of an object is that,
1) Memory allocation for data types of an object is in sequential manner that is in our example, first 4 bytes contains i, next 4 bytes contains j and so on.
2) Memory allocated for an object is only for non static data members of an object.
- We can call member function of the class by using “.” like,
d.fun();
- But if we have a pointer of that class then we can call the member function using arrow operator like,
e.g.
demo *p = new demo();
p->fun();
- In this case, p is a pointer which is of the type of a class demo.
- We allocate a memory dynamically for object of the class demo and base address of that dynamically allocated memory is accepted inside a pointer p and from that pointer p, we can access the member functions as well as data members.
For more reading about technology news in singapore and seo to online marketing do view more about other pages.