Page 310 - Computer_Science_F5
P. 310

float fuelConsumption;
                public:
                   void setMileage(int m) {
                       mileage = m;                                                                Chapter Four: Object oriented programming with C++
          FOR ONLINE READING ONLY
                            }
                   };
              In the context of this example, abstraction can be achieved by using private members
              to hide certain details of the car’s internal workings. The private attributes, such as
              the engine type or fuel consumption, are not directly accessible or modifiable from
              outside the class. Instead, they can only be accessed and modified through public
              (set and get) methods or functions provided by the car class.


              Implementing abstraction in C++

                        Program Example 4.45:

               Code program to demonstrate abstraction in C++

                   #include <iostream>
                   using namespace std;
                   class demoAbstraction {
                   private:
                         int a, b;
                   public:
                         //This method will set values of private members
                         void set(int x, int y)
                         {
                                a = x;
                                b = y;
                         }
                         void display()
                         {
                                cout << “a = “ << a << endl;
                                cout << “b = “ << b << endl;
                         }
                   };
                   int main()
                   {
                         demoAbstraction obj;
                         obj.set(103, 230);
                         obj.display();
                         return 0;
                   }


                                                    301
               Student’s Book  Form Five



     Computer Science Form 5.indd   301                                                     23/07/2024   12:34
   305   306   307   308   309   310   311   312   313   314   315