Set class member field with setter method - C++ Class

C++ examples for Class:Member Field

Description

Set class member field with setter method

Demo Code

#include <iostream>
#include <cstring>        //for strcpy()
using namespace std;
class Product/* w w w.  j av a2s.  c o m*/
{
   private:
       char partname[30];  //name of widget part
       int partnumber;     //ID number of widget part
       double cost;        //cost of part
   public:
       void setpart(char pname[], int pn, double c)
       {
          strcpy(partname, pname);
          partnumber = pn;
          cost = c;
       }
       void showpart()     //display data
       {
          cout << "\nName="   << partname;
          cout << ", number=" << partnumber;
          cout << ", cost=$"  << cost;
       }
};
int main()
{
   Product part1, part2;
   part1.setpart("SQL", 4, 2.55);
   part2.setpart("Java", 9, 4.25);
   cout << "\nFirst part: ";  part1.showpart();  //show parts
   cout << "\nSecond part: "; part2.showpart();
   cout << endl;
   return 0;
}

Result


Related Tutorials