Classes and Objects, Constructors and Desconstructors

Submitted by sylvia.wong@up… on Wed, 02/02/2022 - 00:34

Sub Topics

Welcome to Topic 3

In this topic we will take what we have learned so far about classes and objects to a whole new level. There will be some revision along the way, as we reassert the knowledge foundation and then add to it.

A diagram depicting an application of classes and objects

To your learning on classes and objects, we will add more on:

  • access specifiers
  • defining member functions
  • arrays within classes
  • static data members & member functions
  • array of objects
  • friend function
  • objects as function arguments
  • returning objects
  • pointer to objects
  • pointer to class members.

We will also cover:

Constructors
  • parameterized constructors
  • copy constructor.
Destructors

Before we begin, watch The Cherno explain classes in C++ (The Cherno, 2017) [8:41] to refresh yourself before we get stuck in.

Object-Oriented programming (OOP) and, classes and objects were introduced briefly in a previous topic. Your previous learning will be beneficial throughout this topic as we cover classes and objects in a bit more detail and then introduce constructors and destructors.

Classes in C++ are the building blocks of Object-Oriented programming. A class is a user-defined data type holding its own data members and member functions. These are used when creating an instance of that class. Classes are a good way to group things together and can cut down on coding, in line with the DRY principle (Don’t repeat yourself).

A brief summary of classes:

  • A class is a user defined data type
  • A class is like a blueprint for objects. For example, a cat called Teddy is an object of a class called Cat.
  • Objects are instantiated (created as instances) from the class
  • A class consists of:
    • data members
    • member functions.
  • Data members are the data variables, and member functions are the functions used to manipulate these variables and together data members and member functions defines the properties and behaviour of the objects in a class.
  • Member functions define the meaning of initialisation (creation), copy(), move(), and cleanup() (destruction).
  • A class is defined using the keyword class.
  • A class has a body surrounded by curly brackets {}.
  • Class definitions are terminated with a semicolon ;
  • Members that are public make up the interface, and members that are private make up the implementation.
  • Members are accessed using:
    • . (dot) for objects
    • -> for pointers.
  • Operators such as =, !,and [], can be defined for a class.
  • A class is a namespace containing its members.
  • A struct is a class where members are by default public.
  • Main member access specifiers are public and private.
One bit of advice: it is important to view knowledge as sort of a semantic tree – make sure you understand the fundamental principles, i.e., the trunk and big branches, before you get into the leaves/details or there is nothing for them to hang on to.
Elon Musk

Object-oriented programming allows you to use real life objects in programming. The real-life objects are represented by their attributes and their behaviours.

In her C++ OOP (2020) – Introduction to classes and objects for beginners, Code Beauty uses the following example to explain what a class is:

If a class represents a blueprint, the plans to make a car (not the actual car), an object of the class would be Toyota, Mazda, Ford, BMW and so on.

An attribute (data member) of the Car class would be a name, price, color, or maximum_speed, and a behaviour (member function) would be drive(), brake(), reverse() etc.

How to declare (create) a class

A class is defined in C++ using the keyword class. The body of a call is defined inside the curly brackets and terminated by a semi colon at the end.

An object is an instance of a class. When a class is defined, no memory is allocated, but when it is instantiated (an object is created), memory is allocated. A class is syntactically similar to a structure.

The class is created outside of the main() function. The name of a class is usually written with a capital for each word, for example the general form is:

 

class is the keyword and ClassName is the user defined name of the class. All the functions and variables go inside the curly brackets of the class body.

In the below example a class is created called SimpleClass. SimpleClass contains two data members and two member functions.

Data members:
  • An integer called number
  • A float called cost.
Member functions:
  • Sets the data item to a value
  • Displays the value

The two-member functions provide only access to the data items from outside of the class.

The class is defined in the first part of the program, and later in main(), two objects are defined as instances of SimpleClass. They are called x and y.

The data items of each object are given values during the definition. And the objects also display these values.

Access Specifiers

Functions declared within a class definition are called member functions and may access any element of the class of which they are a part of – this includes private elements. Variables that are part of a class are called member variables or data members.

You may also see the term instance variable used. Access is granted to other areas of a program using the access specifiers.

  • public – members are accessible from outside the class
  • private – members cannot be accessed (or viewed) from outside the class
  • protected – members cannot be accessed from outside the class; however, they can be accessed in inherited classes.

The protected access specifier is needed only when inheritance is involved. Once an access specifier has been used it remains in effect until either another access specifier is encountered, or the end of the class declaration is reached.

Access specifiers modify where the members of a class can be used.

This table, also seen in the previous topic lays out the details of how the access specifiers work on classes.

Access specifiers of OOP
+ Public - Private (default) # Protected
Members can be accessed from inside and outside of the class Members can be accessed only from inside the class Members can be accessed only from inside the class or derived class
animalClass ✓
animalClass ✓
animalClass ✓
            ^

dogClass ✓
 
*friend classes/functions ✓
*friend classes/functions ✓
© Learning Works

All members of a class are private, by default.

private code can only be accessed from code that is within the object, but if you set the code to public, other parts of your program may access it, even if it was defined within an object.

But the information outlined within the private access specifier can be used in the background to fulfil the needs of the code in the public member function. This allows the outside world to interact with the class.

To make parts of a class public you must declare them after the public keyword. All variables or functions after public can be accessed by all other functions in the program. Using the public access specifier means that the information can be displayed on the screen, printed, or seen and accessed by other classes and objects.

Note: Although you can have public variables, good practice dictates that you should try to limit their use and should make all data private, and control access to it through public functions.

When sensitive data is hidden from users, it’s known as encapsulation. It keeps the code and data safe from outside interference and misuse. To achieve encapsulation, you must declare class data members as private.

If you want others to read or modify the value of private members, you can provide public get() and set() methods. We will cover these in more detail later.

Example 1

See the example of encapsulation in the following program from w3schools (n.d.) where the value of an employee’s salary is in the base class with the protected access specifier, meaning it can be accessed within the class and within any inherited classes.

Here, Employee is a simple class that’s used to store an employee’s salary (protected).

When a class is defined, only the specification for the object is defined, no memory or storage is allocated. To use and access functions defined in the class you need to create objects. This is done using the class name and the object you wish to define.

 

Data members and members functions can be accessed using the dot (.) operator with the object. For example, if the name of the object is obj and you want to access the member function called printName() then you will have to write obj.printName()

Learn more about the difference between access specifiers with examples, by watching this Public and Private Access Specifiers | C++ Tutorial.

Get and Set functions

When you want others to read or modify the value of a private member, you can provide public get() and set() methods, as discussed in the Access Specifiers tutorial you just watched.

This example and it’s explanation below are taken from w3schools.com (n.d.).

Example

Example explained

  • The salary attribute is private, so has restricted access.
  • The public setSalary() method takes a parameter (s) and assigns it to the salary attribute (salary = s). void is used for the output data type as there is no output for this function.
  • The public getSalary() method returns the value of the private salary attribute in the form of an integer.
  • Inside main(), we create an object of the Employee class. Now we can use the setSalary() method to set the value of the private salary attribute to 5000. Then we call the getSalary() method on the object to return the value.
A person reading on the laptop in a leather couch.

Now that you have completed the quiz, expand the accordion below to read the full code for the Tesla class and object example.

Defining member functions

Member functions can be defined inside or outside of the class. The body is the same in both situations, but the header is different.

 

Inside the class definition:

The member function declaration is replaced by defining a member function. When a function is defined inside a class, it becomes an inline function.

See the images below of the Tesla class and object example. You will see that the setData() member function is defined outside the class, and the getData() member function is defined inside the class.

Example A

In example A, the highlighted member function getData() is defined inside the class.

Member functions defined inside the class are automatically inline functions. More on inline functions in the next section.

Outside the class definition:

Member functions that are declared inside a class have to be defined separately outside the class.

Example B

In example B, the highlighted member function setData() is defined outside of the class.

Note the following format for defining member functions outside the class definition:

Inline functions

Inline functions in this application cause the compiler to insert/expand/substitute the definition of the function (body) inline when the function is called, during compilation. It is designed to optimise the execution time.

Read Inline functions in C++ (Pravasi, 2018) to learn about the advantages and disadvantages, and the use cases.

Nesting member functions

We told you that a member function of a class can only be called by an object of class using a dot (.) operator.

There is one exception to this rule.

  • A member function can be called inside another member function of the same class by using its name.

Example

Pointer to class members

A pointer to a class member or a pointer-to-member is a special type of pointer that “points” generically to a member of a class, not to a specific instance of that member in an object (CareerRide, n.d.).

We can use pointer-to-member operators .* and ->* to allow you to access a member of a class via a pointer to that member.

Example

Friend Function

When talking about access specifiers previously we talked about private and protected members of a class not being accessible from outside the class, with one exception, friend functions. You can make any function a friend function of a specific class, enabling it to access any and all private members of the class.

Imagine we have created two classes: Manager and Scientist. We want to use a function called income_tax() to operate on the objects of both of these classes. We can have that function made a friend of both classes, thereby allowing the function to have access to their private members. This friend function doesn’t need to be a member of either class.

To make an outside function friendly to a class we have to simply declare this function as a friend.

 

Example 1: Friend function to two classes

Example 2: Friend function

Friend function activity

To complete this activity, you will need to:

  1. Create two classes: Car, and Truck.
  2. Both classes should have a data member for capturing their speed using cin.
  3. Create a friend function void speed() to tell which has greater speed - the Car, or the Truck.

Feedback

Your program might look like this:

Arrays within a class

To refresh the memory, an array is a collection of similar data elements stored at contiguous memory locations, often large amounts. To store this data, we need to define numerous variables. It’s tough memorising all the variable names, so instead it’s better to define an array and store all the elements to it.

Imagine you place an order with the same dealer each month.

The order includes details such as:

  • Item code
  • Number of items
  • Item price.

Let’s perform operations such as:

  • adding an item to the list
  • deleting an item from the list
  • displaying total order value
  • displaying all item codes and prices.

This is the information we want the program to output:

Example 1

You can do the following:

Enter appropriate number
**************************
  - Add an item
  - Display total value
  - Delete an item
  - Display all items
  - Quit
**************************
What is your option? 1
Enter item code: 105
Enter item cost: 10876

Example 2

You can do the following:

Enter appropriate number
**************************
  - Add an item
  - Display total value
  - Delete an item
  - Display all items
  - Quit
**************************
What is your option? 1
Enter item code: 106
Enter item cost: 43876

Example 3

You can do the following:

Enter appropriate number
**************************
  - Add an item
  - Display total value
  - Delete an item
  - Display all items
  - Quit
**************************
What is your option? 4
| Item Code | Item Price |
|-----------|------------|
| 105       | 10876      |
| 106       | 43876      |

To produce the output above, the code would need to look similar to this:

Static members

These are class members that are declared using static keywords.

Static data members:

  • A static data member belonging to a class is shared with all objects of that class, only one copy exists, in the class.
  • It is initialised before any objects are created, before main.
  • Not visible from outside of the class, it lasts for the entire program.

Static member functions:

  • Can only access other static members (data or functions) declared in the same class.
  • As it exists in the class, it is usually called using the class name instead of the object name, as follows:
 

Read how Geeks for geeks outline Static data members in C++ (Geeks for Geeks, 2021).

Class scope and accessing class members

Bisht (2022) explains that when you declare a class, function or variable, its name can only be ‘seen’ and used in specific areas of your program. The context in which it is visible is called its scope.

When you declare a data member s within a member function s it is only visible within that s function, so it has what we call local scope. Where you have different data members by the same name, they will not violate the ‘one definition rule’ if they are in different scopes.

For standard data members, scope also depicts when they are created and deleted or destroyed in memory.

Inside a scope, members are accessible by all member functions and are referenced by name.

Outside a scope, members are referenced through handles, such as an object name, a reference to an object, or a pointer to an object.

Types of scope
A diagram depicting the types of scope in classes
  • Global scope: A global name is one declared outside of any class, function, or namespace.
  • Namespace scope: A name that is declared within a namespace, outside of any class or enumeration definition or function block is visible from declaration to the end of namespace.
  • Local scope: A name declared within a function has local scope. Often referred to as locals. These are visible from declaration to end of the function body.
  • Class scope: Names of class members have scope that extends throughout the class regardless of point of declaration. Class member is also controlled by the public, private, and protected keywords. Public or protected members can be accessed by using the member-selection operators (. or ->) or pointer to member operators (.* or ->*).
  • Statement scope: Names declared in for, if, while, or switch statement are all visible until the end of the statement block.
  • Function scope: A label has scope which means it’s visible throughout a function body even before it is declared. This makes it possible to write statements like goto cleanup before the cleanup label is declared. Variables are only known to the function they are defined in and are deleted once the function is completed.

Read Scopes in C++ (Bisht, 2022) to get a more detailed explanation about scope in C++ with code examples.

Banking activity

Write a program using class name bank, with functions to input value of amount, withdraw, deposited, and display the amount. The output would look something like this:

Option 1: Withdraw

Welcome to NZB

*******************************************************
Enter the initial amount present in your account: 50000

  - Withdraw
  - Deposit

Please select your option: 1

Enter the amount you want to withdraw: 10000
*******************************************************
Final amount present in your account is: 40000
*******************************************************

And option 2: Deposit

Welcome to NZB

*******************************************************
Enter the initial amount present in your account: 60000

  - Withdraw
  - Deposit

Please select your option: 2

Enter the amount you want to deposit: 5000
*******************************************************
Final amount present in your account is: 65000
*******************************************************
 

The program code can be modified using outside class definition functions like this:

 

In the following video The Cherno begins with how to write a class and then in subsequent videos uses this same class information to introduce new concepts so you can see the process of going from a basic version of a class to a more advanced and detailed class.

Class activity

To complete this activity:

  • Review the example program below
  • Write your own program according to the given specifications.

Example program

This program allows the user to enter 5 employees with their name and age and then it displays the list at the end.

Your program specifications

  • Create a class called Order
  • Create three data members:
    • string product
    • double price
    • int qntt
  • Create two member functions:
    • void setData()
    • void getData()

Write the program to get the user to input 4 items on the order and display them at the end.

A programmer with glasses working in a desktop screen.

Objects

A class is a data type that is not used until it is ‘instantiated’ by creating an object from it.

An object is a specific instance of a class that has all the extra information filled in such as the different values of the properties, and what all the methods are going to return.

A UML class diagram of
  • Once a class has been defined, it can be used as a type in objects, arrays, and pointer declarations.
  • An object has the same relationship to a class that a variable has to a data type.
  • An object is an ‘instance’ of a class.
  • Defining objects is like defining a variable of any type.

When a class is defined, only the specification for the object is defined. No memory or storage is allocated. To use the data and access functions defined in the class, objects need to be created. The syntax for an object is: ClassName ObjectName;

A diagram depicting the concept and application of objects
© Learning Works

In the first example, each object here contains data with two member functions and is linked to the other objects. The second example gives a real-life example of how each object is used.

Have you worked in an organisation or studied with a provider which gives you access to different areas of a software program? Or maybe you use an authenticator app that allows you access into a particular area of a website? This is what a simple diagrammatic structure of that program looks like on the planning side, and when you’re developing any coded program, app, or game, you will want to have a sound understanding of what areas of the program different users will access and how they want to or need to interact and use the access they are given. It may be that they need a password, they may need to input information, or they may want to extract information.

Knowing how the user will interact with the program is essential and knowing what the user will not be given free access to is equally important.

Example

We will reuse the class code used previously called SimpleClass. In the highlighted int main() area are two objects defined from the class SimpleClass.

Example explained

Let’s take a closer look at the code in this example. The class SimpleClass defined in this program contains two data members and two member functions. These two member functions provide the only access to the data members from outside the class.

  1. The first member function sets the values of the data members
  2. The second member function displays the values.

In SimpleClass, the class—whose name is SimpleClass—is defined in the first part of the program. Later, in main(), we define two objects—x and y—that are instances of that class.

Each of the two objects are given values, and each displays its value. Here’s the output of the program:

object x
number: 15
cost: 89.5

object y
number: 27
cost: 192.2

Array of objects

In C++, you can declare an array of any data type. This also includes the class type. The Array of objects is an array containing the elements of the class type. The definition of an array of objects is like the usual array definition with the data type replaced with the class name. The syntax for declaring and using an object array is the same as it is of any other type of array.

The following syntax is used to define an array of objects and contains 20 elements of the type class name. The elements contained in this declaration are the same as if the objects were declared separately. Here, obj1, obj2, obj3 and the others all the way to obj20 are in this one declaration.

 

For Example: This program has an array of objects that contains 3 object elements.

This program displays the numbers 1, 2, and 3 on the screen.

If a class defines a parameterised constructor, you may initialise each object in an array by specifying an initialisation list, just like you do for other types of arrays. However, the exact form of the initialisation list will be decided by the number of parameters required by the object’s constructors. For objects whose constructors have only one parameter, you can simply specify a list of initial values, using the normal array-initialisation syntax.

Objects as function arguments

You can pass the objects of a class as arguments in C++ in the same way you pass a variable to a function as arguments.

An object can be passed as an argument to a member function, a friend function and a non-member function. Remember that the private and public members of the object are accessible to the member function and the friend function, however the non-member function is only allowed to access the public members of the object (Simplilearn, 2022).

There are two ways an object may be used as function arguments:

  • Pass-by-value – A copy of the object is passed to the function
    • When a copy of the object is passes to the function, any changes made to the object inside the function do not affect the object used to call the function.
  • Pass-by-reference – Address of the object is passed to the function
    • When an address of the object is passed, the called function works directly in the actual object used in the call. Changes made to the object through the function will reflect in the actual object.

Void someFunction(he type& name)

The pass-by-reference method is more efficient since it requires to pass only the address of the object and not the entire object but remember that the actual object will be affected by changes made by the function.

Returning objects

When an object is returned by a function, a temporary object is automatically created that holds the return value. It is this object that is returned by the function.

After the value is returned, this object is destroyed.

Pointer to objects

Just as there are pointers to other types of variables, you can have pointers to objects. When accessing members of class given a pointer to an object, use -> operator instead of the dot . operator.

Object pointers are useful in creating objects at run time. We can also use an object pointer to access the public members of an object.

 

Is equivalent to:

 

Or:

 

Simplilearn (2022) has a comprehensive Introduction to classes and objects in C++ that outlines the role of objects and the significance of classes and objects in C++ programming. Read the article to find program explanations and examples.

Programming practice

Example – transposing a matrix

In this example, we are taking in 9 integers from the console which produces a matrix of 3 by 3. Then the program transposes the matrix for us.

Practice – class and object

Now it’s your turn.

  • Create a program with a class called Animal which
    • has data members for animal type (wild/domestic) and animal category
    • has a function asking for inputs for animal type and animal category
    • has a function that prints to the console "The animal type is: xxx", and "The animal category is: yyy"
  • Create an object that calls both functions from the class.

Answer

Finally, to reinforce what you’ve learned so far, watch The Cherno (2017) outline how to create/instantiate objects in C++. This is a comprehensive video that goes into lots of useful detail.

What is a constructor?

A constructor is a special member function of a class with no return type, which initialises objects of a class. It creates the environment in which the member functions operate. Sometimes creating that environment involves acquiring a resource such as a file, or some memory which must be released (destroyed) after use.

By defining a constructor, we can specify how an object of a class is to be initialised. To compliment constructors, we can define a destructor to ensure cleanup, if it goes out of scope for example.

In C++ Constructor is automatically called when an object (instance of a class) is created.

Constructors are different from normal functions in the following ways:

  • A constructor has the same name as the class itself
  • Default constructors don’t have an input argument, but Copy and Paramaterised constructors have input arguments
  • Constructors don’t have a return type
  • A constructor is automatically called when an object is created
  • It must be in the public section of a class
  • If not specified, the compiler generates a default constructor for the object (it expects no parameters and has an empty body).

Kariya (2021) summarises that “constructors are special class members which are called by the compiler every time an object of that class instantiated. Constructors have the same name as the class and may be defined inside or outside the class definition.”

To create a constructor, use the same name as the class, followed by parenthesis

Example

Notes:

  • the constructor has the same name as the class
  • the constructor is always public
  • the constructor doesn’t have a return value.

Watch The Cherno explain Constructors in C++ (The Cherno, 2017) to learn more and then we’ll continue with the different types of constructors.

Constructor types
  • Default constructors don’t take any arguments, has no parameters.
  • Parameterised constructors typically help initialise an object when it’s created.
  • Copy constructors.

Let’s use a real-world experience to explain the difference between the different types of constructors.

Imagine you go into a shop and ask for a cup. The storekeeper gives you a cup, any cup - that is like a default constructor.

A paper cup on a wooden bench or table

Imagine you go into a shop and ask for a cup that is black, has a handle, and holds 300ml. The storekeeper gives you a cup that matches your requirements – that is like a parameterised constructor. Imagine you go into a shop and show the storekeeper a cup you already have and ask him for one exactly like it. The storekeeper gives you a cup that is an exact replica of your one – that is like a copy constructor.

Example – Default constructor

Even if we don’t define any constructor explicitly, the compiler will automatically provide a default constructor implicitly.

Example – Parameterised Constructor

To create a parameterised constructor simply add parameters to it just like you would with any other function. When you define the constructor’s body, use the parameters to initialise the object.

When an object is declared in a parameterised constructor, the initial values have to be passed as arguments to the constructor function. The normal way of object declaration may not work. The constructors can be called explicitly or implicitly.

You can use a parameterised constructor to initialise the various data elements of different objects with different values when they are created. It is also used to overload constructors. Constructor over loading is where there is more than one constructor in a class.

Example – Copy Constructor

This is a constructor that creates a new object and copies its argument into it. It’s used to declare and initialise an object from another object. A copy constructor takes a reference to an object from the same class as itself as an argument.

 

Or:

 

Or:

 

Constructor defined inside class

Example

Constructor defined outside class

When defining the constructor outside the class, first declare the constructor inside the class and then define it outside of the class by specifying:

 

Knowing where to find other resources to help you learn and expand your knowledge is crucial. Let’s finish this Constructors section by checking out another Buckys programming tutorial - this one is dedicated to explaining constructors, what they are and why they are useful. Bucky has such a great way of making it all so simple and clear.

A destructor is a member function used to clean up an object of a class. It’s invoked directly when the object goes out of scope or is explicitly destroyed by a call to delete.

Destructors:
  • are member functions of class
  • perform termination housekeeping before the system reclaims the objects memory
  • compliment the constructor
  • receive no parameters and return no value (or void).
  • do not accept arguments
  • can only be one destructor per class
  • do not allow overloading.

The purpose of destructors:

  • Free dynamic storage pointed to only by members of object
  • Reduce reference when object disappears
  • Safely close things and release memory, for example files

How do you differentiate a destructor from a normal function?

A destructor has the same name as the class and is preceded by a tilde (~) For example the destructor for a class called Time, would be ~Time() {}

It is also important to note that destructors don’t take arguments and don’t give them back.

 

A destructor can’t be overloaded. If we don’t write our own destructor the compiler generates one. If we have dynamically allocated memory or a pointer in the class, the default destructor works fine. We can write a destructor to release memory before the class instance is destroyed when a class includes a pointer to memory allocated in the class. To prevent memory leaks, this must be done.

When Constructors and Destructors are called

Destructors are called when one of the following events occurs:

  • Just before an object goes out of scope.
  • An object is deallocated using delete.
  • An object’s lifetime ends.
  • A program ends and global or static objects exist.
  • The destructor is explicitly called using the destructor function's fully qualified name.

Destructors can freely call class member functions and access class member data.

There are two restrictions on the use of destructors:

  • You cannot take its address.
  • Derived classes do not inherit the destructor of their base class.

A class needs a destructor if it acquired or calls on a resource, as to manage the resource safely it probably must implement a copy constructor and a coy assignment. If these special functions aren’t defined by the user, the compiler will implicitly define one.

Rules for C++ Destructors

A person walking through some rules for C++ destructors to a teammate

According to C++, destructor the statement should begin with a tilde (~) and the same class name.

  1. Destructors are not equipped with parameters or a return form.
  2. Destructors are invoked automatically and cannot be invoked manually from a program.
  3. Destructors cannot be overloaded.
  4. Which can be a virtual destructor.
  5. The Destructor will execute the reverse order of object creation.
  6. Destructor can only be in the public section.

C++ destructors are class members that remove an object. They are named when the class object is no longer in view, for example when a method, program, or delete variable is called. Destructors are different from member functions in that they do not accept any arguments and do not return anything.

You can read more about constructors and destructors in the visual studio 2022 Microsoft build site. There is a comprehensive library of help and build information on declaring and using destruction calls.

Your final activity for this topic is creating a program. Read the instructions below and write a program that gives outputs similar to the example outlined.

The Ocean Race 2021-22 route is announced

Yachts are ready to sail and will visit 10 international cities, including the start port and the Grand Finale finish in Genoa, Italy. In ocean navigation, degrees and minutes (for latitude and longitude) are used to measure locations along with the direction. Degrees of latitude are either north (N) or south (S) measured from 0 to 180 degrees and degrees longitude are either east (E) or west (W) measured from 0 to 90. Example: 38°56’N, 71°0’W is 38 degrees 56 minutes North and 71 degrees 0 minutes West.

See the sample output below before you begin programming.

Task:

  1. Write a program with a class Yacht that allows for yachts’ numbers and locations.
    1. For Yacht's Number:
      1. You will number each yacht object as it is created using a constructor. To do this, you will have a data member that holds a serial number for each object created from the class.
      2. Then you will need another data member that records a count of how many objects have been created so far.
    2. For Yacht’s Location:
      Create a class Location that has three data members:
      1. int for degrees (explained above)
      2. float for minutes (explained above)
      3. Char for direction letters N, S, E, W (explained above)
    3. Location class includes a member function [ getpos() ] which obtains a location value in degrees (between 0-180) and minutes (between 0 to 60) and direction (N, S, E, W) from the user and stores this in an object.
    4. Another member function [ display() ] should report the yacht number and location using two variables from the Location class in this format: 148°26’ N.
    5. The main() program creates three yachts, asks the user to input the location and then displays each yacht's number and location.
  2. Prepare the UML (flowchart) class diagram for the Location class.

Note: Use the hex character constant ‘\xF8’ to display a degree symbol (°).

Note: Read this tutorial from Visual paradigm to access a tutorial on creating a UML Class diagram if you need to.

Sample Output:

***************Ocean Race 2021-22***************
**************************************
Enter the Location of the first ship:
Input degrees between 0 and 180: 120
Input minutes between 0 and 60: 45
Input direction (E/W/N/S) : E 
Input degrees between 0 and 180: 34
Input minutes between 0 and 60: 56
Input direction (E/W/N/S) : N
**************************************
Enter the Location of the second ship:
Input degrees between 0 and 180: 34
Input minutes between 0 and 60: 12
Input direction (E/W/N/S) : W 
Input degrees between 0 and 180: 78
Input minutes between 0 and 60: 34
Input direction (E/W/N/S) : S
**************************************
Enter the Location of the third ship:
Input degrees between 0 and 180: 179
Input minutes between 0 and 60: 23
Input direction (E/W/N/S) : E 
Input degrees between 0 and 180: 126
Input minutes between 0 and 60: 45
Input direction (E/W/N/S) : S
***************Welcome to Ocean Race 2021-22***************

The ship serial number is :1
and it's position is 34℃56 N Latitude 120℃45 E Longtitute

The ship serial number is :2
and it's position is 78℃34 N Latitude 34℃12 E Longtitute
Module Linking
Main Topic Image
A programmer seated at their desk, casually working on their organisation's codebase.
Is Study Guide?
Off
Is Assessment Consultation?
Off