Table of Contents
Object Oriented Programming is the Programming Concept or Programming Paradigm which is used to Increase the flexibility of your code and limit the accessibility for security purpose by providing concepts like Inheritance & Polymorphism which you will learn in this tutorial, OOPs are used in most Programming Languages such as C++, Python, PowerShell, Ruby, etc.
Object Oriented Programming is a type of Programming Paradigm or Style in which operations revolve around class & objects.
What is a Class & object in OOPs?
So What is an object? The object is an entity that has some state or properties and behavior and an object is an instance of a Class. everything around you can be consider as an object since it has some some state or properties and behavior.
Now, What is a Class? A class can be defined as a Template or blueprint of the methods and variables of a particular kind of object. A class is a user-defined datatype it means that a user can customize the properties of an object by making significant changes in a class.
How to Create a Class?
To create a Class, You have to use the keyword “class” before the name of your class and always remember everything is case-sensitive in C++, So don’t misunderstood “class” by “Class”.
#include<iostream>
using namespace std;
//definition of a class
class class_Name{
};
int main(){
//Instance of a class
class_Name object1;
}
Memory Allocation
Here “object1” is an object of type “class_Name”, always remember a class doesn’t allocate any memory when it is created but when an object is created, memory is allocated to hold the properties, below is a code given to demonstrate how much memory is being allocated during this process.
#include<iostream>
using namespace std;
class class_Name{
public:
int data;
};
int main(){
class_Name object1;
cout<<sizeof(object1.data)<<endl;
}
Output
4
Here “public” is an Access Modifier about which we will learn further since int datatype allocates memory of 4 bytes which can vary over different types of the compiler you are using,
#include<iostream>
using namespace std;
class class_Name{
};
int main(){
class_Name object1;
cout<<sizeof(object1.data)<<endl;
}
Output
1
Above code demonstrate that in the case of an empty class, the object allocated with a memory of “1 byte” .
Class in a new file
We can define a class in a new file, and include it where we need it:
// this file is named as Student.cpp
class Student{
public:
int rollNo=12;
int Age=18;
};
The Above file is a class definition named “Student.cpp” this can be saved separately on your IDE (Integrated Development Environment) and when we want to use the properties of this Class we can include it in our current file, given below is a practical approach of this method:
#include<iostream>
//here we are including the class file
#include"Student.cpp"
int main(){
Student Ajay;
cout<<Ajay.rollNo<<endl;
cout<<Ajay.Age<<endl;
return 0;
}
Output
12 18