Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletter Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds
Arrow up icon
GO TO TOP
C++ Fundamentals

You're reading from   C++ Fundamentals Hit the ground running with C++, the language that supports tech giants globally

Arrow left icon
Product type Paperback
Published in Mar 2019
Publisher
ISBN-13 9781789801491
Length 350 pages
Edition 1st Edition
Languages
Arrow right icon
Authors (2):
Arrow left icon
 Mallia Mallia
Author Profile Icon Mallia
Mallia
 Zoffoli Zoffoli
Author Profile Icon Zoffoli
Zoffoli
Arrow right icon
View More author details
Toc

Table of Contents (8) Chapters Close

About the Book 1. Getting Started FREE CHAPTER 2. Functions 3. Classes 4. Generic Programming and Templates 5. Standard Library Containers and Algorithms 6. Object-Oriented Programming 1. Appendix

Lesson 3: Classes

Activity 7: Information Hiding Through Getters and Setters

  1. Define a class named Coordinates with its members under a private access specifier:

    class Coordinates {

      private:

        float latitude;

        float longitude;

    };

  2. Add the four operations as specified above and make them publicly accessible by preceding their declaration with the public access specifier. The setters (set_latitude and set_longitude) should take an int as a parameter and return void, while the getters do not take any parameter and return a float:

    class Coordinates {

      private:

        float latitude;

        float longitude;

      public:

        void set_latitude(float value){}

        void set_longitude(float value){}

        float get_latitude(){}

        float get_longitude(){}

    };

  3. The four methods should now be implemented. The setters assign the given value to the corresponding members they are supposed to set; the getters return the values that are stored.

    class Coordinates {

      private:

        float latitude;

        float longitude;

      public:

        void set_latitude(float value){ latitude = value; }

        void set_longitude(float value){ longitude = value; }

        float get_latitude(){ return latitude; }

        float get_longitude(){ return longitude; }

    };

    An example is as follows:

    #include <iostream>

    int main() {

      Coordinates washington_dc;

      std::cout << “Object named washington_dc of type Coordinates created.” << std::endl;

      

      washington_dc.set_latitude(38.8951);

      washington_dc.set_longitude(-77.0364);

      std::cout << “Object’s latitude and longitude set.” << std::endl;

      

      std::cout << “Washington DC has a latitude of “

      << washington_dc.get_latitude()

      << “ and longitude of “ << washington_dc.get_longitude() << std::endl;

    }

Activity 8: Representing Positions in a 2D Map

  1. The first step is to create a class named Coordinates containing the coordinates as data members. These are two floating-point values, _latitude and _longitude, which identify the coordinates on a geographic coordinate system. Additionally, these data members are initialized with a private access specifier:

    class Coordinates {

      private:

        float _latitude;

        float _longitude;

    };

  2. Then, the class is extended with a public constructor which takes two arguments used to initialize the data members of the class:

    class Coordinates {

      public:

        Coordinates(float latitude, float longitude)

        : _latitude(latitude), _longitude(longitude) {}

      private:

        int _latitude;

        int _longitude;

    };

  3. We can also add getters as seen previously to access the class members. An example is as follows:

    #include <iostream>

    int main() {

      Coordinates washington_dc(38.8951, -77.0364);

      std::cout << “Object named washington_dc of type Coordinates created.”

      << std::endl;

      

      std::cout << “Washington DC has a latitude of “

      << washington_dc.get_latitude()

      << “ and longitude of “ << washington_dc.get_longitude()

      << std::endl;

    }

Activity 9: Storing Multiple Coordinates of Different Positions in the Map

  1. Using the RAII programming idiom, write a class that manages memory allocation and deletion of an array of int. The class has an array of integers as member data, which will be used to store the values.

    The constructor takes the size of the array as a parameter.

    The constructor also takes care of allocating memory, which is used to store the coordinates.

  2. Finally, define a destructor and make sure to free the previously allocated array in its implementation.
  3. We can add print statements to visualize what is happening:

    class managed_array {

      public:

        explicit managed_array(size_t size) {

          array = new int[size];

          std::cout << “Array of size “ << size << “ created.” << std::endl;

        }

      ~managed_array() {

        delete[] array;

        std::cout << “Array deleted.” << std::endl;

      }

      private:

        int *array;

    };

  4. We can use our managed_array class as follows:

    int main() {

        managed_array m(10);

    }

    The output will be as follows:

    Array of size 10 created.

    Array deleted.

Activity 10: The AppleTree Class, which Creates an Apple Instance

  1. First, we need to create a class with a private constructor. In this way, the object cannot be constructed, because the constructor is not publicly accessible:

    class Apple

    {

      private:

        Apple() {}

        // do nothing

    };

  2. The AppleTree class is defined and contains a method called createFruit that is in charge of creating an Apple and returning it:

    #include <iostream>

    class AppleTree

    {

      public:

        Apple createFruit(){

          Apple apple;

          std::cout << “apple created!” << std::endl;

          return apple;

        }

    };

  3. If we compile this code, we will get an error. At this point, the Apple constructor is private, so the AppleTree class cannot access it. We need to declare the AppleTree class as a friend of Apple to allow AppleTree to access the private methods of Apple:

    class Apple

    {

      friend class AppleTree;

      private:

        Apple() {}

        // do nothing

    }

  4. The Apple object can now be constructed using the following code:

    int main() {

      AppleTree tree;

      Apple apple = tree.createFruit();

    }

    This prints the following:

    apple created!

Activity 11: Ordering Point Objects

  1. We need to add an overload for the < operator to the Point class that we have previously defined. This takes another object of type Point as an argument and returns a Boolean indicating whether the object is less than the one provided as the parameter, using the previous definition for how to compare the two points:

    class Point

    {

      public:

        bool operator< (const Point &other){

          return x < other.x || (x == other.x && y < other.y);

        }

      int x;

      int y;

    };

  2. At this point, we are able to compare the two Point objects:

    #include <iostream>

    int main() {

      Point p_1, p_2;

      p_1.x = 1;

      p_1.y = 2;

      p_2.x = 2;

      p_2.y = 1;

      std::cout << std::boolalpha << (p_1 < p_2) << std::endl;

    }

  3. Since in our example p_1.x is initialized to 1 and p_2.x to 2, the result of the comparison will be true, which indicates that p_1 comes earlier than p_2 in the order.

Activity 12: Implementing Functors

  1. Define a class constituted by a private data member of type int and add a constructor to initialize it:

    class AddX {

      public:

        AddX(int x) : x(x) {}

      private:

        int x;

    };

  2. Extend it with the call operator operator() which takes an int as a parameter and returns an int. The implementation in the function body should return the addition of the previously defined x value and the parameter of the function named y:

    class AddX {

      public:

        AddX(int x) : x(x) {}

        int operator() (int y) { return x + y; }

      private:

        int x;

    };

  3. Instantiate an object of the class just defined and invoke the call operator:

    int main() {

      AddX add_five(5);

      std::cout << add_five(4) << std::endl;

    }

    The output will be as follows:

    9

lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at £13.99/month. Cancel anytime
Visually different images