Write your question here.
hey guys, ive a question between setter and getter...ive written two codes. The first is a combination with set and get..and the second just with set..so what is difference ? When shall I work with set and get together and when without get ?
I am confuse :/
Thanks for ur help :D
//First code
# include <iostream>
# include <string>
using namespace std;
class setandget {
int age;
public:
void set(int x){
age=x;
}
int get(){
return age;
}
};
int main ()
{
setandget r;
r.set(5);
cout<<" child is now "<<r.get()<<"years old"<<endl;
return 0;
}
// Second code
# include <iostream>
# include <string>
using namespace std;
class circle{
int radius;
public:
//circle(int t);
void setradius(int x);
void print();
int getradius();
};
void circle::setradius(int x){
radius=x;
}
void circle::print(){
cout<<" radizs ise "<<radius;
}
int circle::getradius(){
return radius;
}
int main(){
circle r;
r.setradius(6);
r.print();
circle r2;
r2.setradius(5);
cout<<"child is now "<<r2.getradius()<<"years old";
return 0;
}
Both of the samples have setters and getters present.
This style of coding is very useful, especially in the context of OOP. Say you have a resource(a database) in a class, and you would want to print a particular entry in the db, you would not want to give the database as a whole to something outside the class. Here, you would just use a getter to do the job as in the second example.