Home » C++ programs

C++ | Create a class with setter and getter methods

Here, we are going to learn how to create a class with setter and getter methods in C++ programming language?
Submitted by IncludeHelp, on March 01, 2020

In the below program, we are creating a C++ program to create a class with setter and getter methods.

#include <iostream>

using namespace std;

// class definition
class Pofloat {
  private: // private data members
    float x, y;

  public: // public member functions
    void set_xy(float x, float y);
  float get_x();
  float get_y();
};

// member functions definitions
void Pofloat::set_xy(float x, float y) {
  this -> x = x;
  this -> y = y;
}

float Pofloat::get_x() {
  return x;
}

float Pofloat::get_y() {
  return y;
}

// main function
int main() {
  // creating objects
  Pofloat objP;

  //setting the values
  objP.set_xy(36.0f, 24.0f);
  //getting the values
  cout << "objP is " << objP.get_x();
  cout << ", " << objP.get_y() << endl;

  //setting the values again
  objP.set_xy(1.2f, 3.4f);
  //getting the values again
  cout << "objP is " << objP.get_x();
  cout << ", " << objP.get_y() << endl;

  return 0;
}

Output

objP is 36, 24
objP is 1.2, 3.4

See the program – here method set_xy() which is a setter method that is using to set the value of x and y and get_x(), get_y() are the getter methods that are using to get the value of x and y.






Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.