OOPS Concepts in C++
OOP – Object Oriented Programming. It is a programming approach which deals with objects and classes. It creates reusable code to achieve modularity.
Why OOPs concepts?
- It makes the code modular.
- The code can be reusable any times.
- It is scalable.
- It gives you security from unauthorized access.
OOPs concepts:
The concepts are listed below.
Each one of the concepts are explained with code as follows…
1.Class:
It is a
prototype from which the object are created. It has a collection of variables
and methods.you can create multiple objects for single class. The class has
following components.
Class Components:
- Class name: Name of the class.
- Access specifiers: private, public and protected
- Methods: it defines the functionalities.
- Variables: it deals with values.
- Constructors: it initializes the values.
- Body: it contains the code of the class.
Eg:
Class class_name {
Access specifier:
Datatype variable1;
…………………………….
Datatype variablen;
Access specifier:
Constructor:
……………………..
//get() methods
……………………..
//set() methods
………………………
//other methods
……………………….
}
main()
{
………………………
}
2. Object:
An object is a real
world entity. Using the class, the objects are created. The object has some
properties.
State: The data members reflects for the object.
Behaviour: it is response of object to other objects.
Member function: it performs a specific task.
Identity: it is the unique name of object.
Let us create a c++ program to use class and object.
C++ program:
#include <iostream>
#include <string>
using namespace std;
class Student {
// variable declaration
private:
string s_name;
string s_id;
string s_year;
// Constructor
initialisation
Student(string
s_name,string s_id,string s_year) {
this->s_name = s_name;
this->s_id
= s_id;
this->s_year = s_year;
}
string getName() {
return s_name; }
string getId() {
return s_id; }
string getYear() {
return s_year;}
void
setName(string s_name) { this->s_name = s_name; }
void setId(string
s_id) { this->s_id= s_id; }
void
setYear(string s_year) {this->s_year;}
// Instance method
void displayIt() {
cout <<
"Name: " << s_name << endl;
cout <<
"Id: " << s_id << endl;
cout <<
"Year: "<< s_year <<endl;
}
};
string
s_name,s_id,s_year;
cout<<"Enter the details:"<<endl;
cout
<<"Enter the name: " <<endl;
cin>>s_name;
cout
<<"Enter the id: " <<endl;
cin>>s_id;
cout
<<"Enter the year: " <<endl;
cin>>s_year;
Student
ss(s_name,s_id,s_year);
ss.displayIt();
return 0;
}
Output:
Enter the details:
Enter the name:
Jey
Enter the id:
Q1
Enter the year:
I
Name: Jey
Id: Q1
Year: I
This is the basic of OOPs concept. In this blog, class and
object are explained with examples. Remaining concepts are explained in next
post.
Comments
Post a Comment