Q:

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

belongs to collection: C++ Classes and Object programs

0

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

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

n 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.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

C++ Classes and Object programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
C++ program to create a class to read and add two ... >>
<< C++ | Create an empty class (a class without data ...