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 [Last updated : March 01, 2023]

Creating a class with setter and getter methods in C++

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

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.



Related Programs



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.