My C++ Journey : OOP
I had learned C++ few years ago at university. But, I was not happy with OOP concepts. Even during Java Data structures subject , I often heard about setters
and getters
. I was literally completing assignments with the help of friends.
From that time, when someone says OOP, I feel uncomfortable. Recently I got my annual leaves and decided to complete some C++ on Udemy as my original plans got destroyed by Covid-19. Even there I felt the same when I am about to take OOP.
Somehow after seeing same video few times, finally I understood getters
and setters
. Here its as I understood. Following all things are only my own thoughts, readers should not take these are 100% technical.
In OOP, a class is like a place we define similar characteristics in once place. If we get an university, we can list students, faculties, lectures into separate classes as they have unique features. As an example, lets get a student. A student can have following characteristics.
name : string
age : int
specialization : string
gpa : double
All these 4 things are private for a student. When we define Student class :
using namespace std;class Student {
private:
int age;
string specialization;
double gpa;public:
string name;
};
As it says, 3 variables are private and name is public for a student. Private variables can not use outside the class declaration. As they are private for that block. Therefor we need getters and setters to work with those private variables.
When we define a student object from this class, we have to use special setters
and getters
to work with those. For simplicity lets get age
variable and make setter and getter function to set and get age value.
using namespace std;class Student{
private:
int age;
string specialization;
double gpa;public:
string name;
void setStudentAge(int);
int getStudentAge();};void Student::setStudentAge(int age){
this->age = age;
}int Student::getStudentAge(){
return age;
}
setStudentAge
function will set student age and getStudentAge
will return student’s age. Without these setters and getters we can not access to age variable. Final working sample would be similar to.
#include <iostream>
using namespace std;class Student{
private:
int age;
string specialization;
double gpa;public:
string name;
void setStudentAge(int);
int getStudentAge();};void Student::setStudentAge(int age){
this->age = age;
}int Student::getStudentAge(){
return age;
}int main(int argc, char const *argv[])
{
Student sachith; // creating Student object sachith.setStudentAge(30); // setting student's age sachith.getStudentAge(); // getting student's age return 0;
}
I hope this is useful for someone who has issues with OOP concepts.
Thanks for reading… Stay safe!