Page 302 - Computer_Science_F5
P. 302

Creating a class in C++

                      Program Example 4.40:
               Syntax and structure for class                                                      Chapter Four: Object oriented programming with C++

          FOR ONLINE READING ONLY
                             class Car {     // This is class

                             public:           // This is access specifier
                                   void drive() {
                                       // The code to drive the car will be put here
                                   }
                             private:

                                   int speed;
                                   int amountOfCoolant;
                             };



              The keyword “class” is used to create a class named Car. The keyword “public”
              serves as an access specifier, indicating that the attributes and methods of the class
              can be accessed from outside the class. Private members declared under the “private”
              specifier can only be accessed and modified from within the class itself. They are not
              accessible or modifiable from outside the class, except for certain exceptions like
              friend classes or functions that have been given special access.


              There are two variables in class “Car”, speed and amountOfCoolant, both  of type
              integer. These variables are referred to as attributes when declared within a class.
              Finally, the class definition is concluded with a semicolon (;).


              Object in C++
              An object is an instance of a class. When you create an object, you are creating the
              actual instance based on your class blueprint. For , example the piece of program
              code shows method to create object:
                    Car yourObject; // This code is creating an object of the Car class

                    yourObject.drive(); // This code is calling a method on the object

              Creating object in C++
              To create an object in C++, you need to use a class. To create an object of the Mmea
              class in Program Example 4.41, you have to specify the class name followed by the


                                                    293
               Student’s Book  Form Five



     Computer Science Form 5.indd   293                                                     23/07/2024   12:34
   297   298   299   300   301   302   303   304   305   306   307