Compounded Types in C++

Compounded Types in C++

Welcome to the another C++ article where we will uncover the language’s flexibility and power through various data types. In this article, we’ll explore the compounded types such as Enumerated Types, Simple Structures, Very Simple Classes, the intriguing concept of the union and Type Conversions in C++. So, buckle up, aspiring programmers, as we embark on a journey to demystify these essential building blocks of C++.

Table of Contents

Enumerated Types

Let’s kick things off with Enumerated Types, a feature that allows you to create your own data type with a set of named values. Think of it as a way to make your code more readable and self-explanatory. For example:

Sometimes we need to handle limited set of values which can be referred by labels. For example the day of week, year names etc…

i.e. enum week{Mon, Tue, Wed, Thu, Fri, Sat, Sun} this_week;

This concept in C++ is called enumeration. Here this_week is the variable of enum type week.

enum Color { RED, GREEN, BLUE };
Color myFavoriteColor = GREEN;

Here, we’ve defined a custom type “Color” with three possible values. It’s like having a palette of colors at your disposal, making your code cleaner and easier to understand.

A Simple Structure

Structures provide a way to group variables of different data types under a single name. Consider this straightforward example:

struct Point {
    int x;
    int y;
};

Point myPoint = { 3, 7 };

Here, we’ve created a structure named “Point” with two integer members, ‘x’ and ‘y’. The instance “myPoint” holds the coordinates (3, 7). Structures are handy when you need to bundle related information together.

A Simple Class

Now, let’s step into the realm of classes, a fundamental concept in object-oriented programming (OOP). Classes allow you to model real-world entities and their behaviors. Here’s a minimalistic example of a Class in C++:

class Circle {
public:
    double radius;
    double calculateArea() {
        return 3.14 * radius * radius;
    }
};

Circle myCircle;
myCircle.radius = 5.0;
double area = myCircle.calculateArea();

In this snippet, we’ve defined a class “Circle” with a public member “radius” and a method “calculateArea.” Creating an instance “myCircle” and setting its radius allows us to compute the area of the circle easily. Classes pave the way for organized and reusable code.

The class is a type which can be used to declare objects in much the same way that a structure is a type that can be used to declare variables.

The Union in C++

Let’s delve into the intriguing concept of the union in C++. Unions allow you to store different data types in the same memory space, sharing the same starting point. A union in C++ goes a step further by allowing overlapping members. Here’s a glimpse:

union MyUnion {
    int intValue;
    float floatValue;
};

MyUnion myData;
myData.intValue = 42;
cout << "Integer value: " << myData.intValue << endl;
cout << "Float value: " << myData.floatValue << endl;

In this example, we’ve created a union “MyUnion” with an integer and a float member. By setting the integer value, we can access the same memory location as a float, showcasing the flexibility and efficiency of unions. In ANSI-C, all unions must be named in order to be used, but this is not true in C++. When using C++ we can use a free union, a union without a name.

C++ Type Conversions

Type conversion, also known as type casting, in C++ refers to the process of converting a value from one data type to another. C++ is a statically-typed language, which means that the data type of a variable must be declared before it is used. However, there are situations where it becomes necessary to convert a value from one type to another, either implicitly by the compiler or explicitly by the programmer.

#include <iostream.h>

int main()
{
  int a = 2;
  float x = 17.1, y = 8.95, z;
  char c;

  c = (char)a + (char)x;
  c = (char)(a + (int)x);
  c = (char)(a + x);
  c = a + x;

  z = (float)((int)x * (int)y);
  z = (float)((int)x * (int)y);
  z = (float)((int)(x * y));
  z = x * y;

  c = char(a) + char(x);
  c = char(a + int(x));
  c = char(a + x);
  c = a + x;

  z = float(int(x) * int(y));
  z = float(int(x) * int(y));
  z = float(int(x * y));
  z = x * y;
}

The type conversions are done in C++ in exactly the same manner as they are done in ANSI-C, but C++ gives you another form for doing the conversions.

Let’s take a closer look at the key portions of the program to unravel the nuances of type conversions.

The Familiar “Cast” Form – Explicit Type Conversion

c = (char)a + (char)x;
c = (char)(a + (int)x);
c = (char)(a + x);
c = a + x;

In these lines, the familiar “cast” form of type conversions from ANSI-C is used. The cast operator (type) is employed to explicitly convert variables of one type to another. For instance, the integer ‘a’ is first converted to a float before being added to ‘x’, and then the result is cast to a char.

C++ Style Type Coercion – Implicit Type Conversion

c = char(a) + char(x);
c = char(a + int(x));
c = char(a + x);
c = a + x;

In these lines, we see the unique C++ style of type coercion. The conversions are written as function calls, resembling a more intuitive approach. The key difference is that the type conversions are expressed as if they were functions. While lines 20-28 are functionally identical to lines 10-18, the syntax offers an alternative, potentially clearer way to handle type conversions in C++.

C++ provides specific casting operators: static_cast, dynamic_cast, const_cast, and reinterpret_cast. These casting operators offer more safety and clarity than C-style casting.

Type conversion is a powerful feature in C++, but it should be used judiciously to avoid unexpected behavior and ensure the integrity of the program. Understanding when and how to perform type conversions is essential for writing robust and maintainable C++ code.

M. Saqib: Saqib is Master-level Senior Software Engineer with over 14 years of experience in designing and developing large-scale software and web applications. He has more than eight years experience of leading software development teams. Saqib provides consultancy to develop software systems and web services for Fortune 500 companies. He has hands-on experience in C/C++ Java, JavaScript, PHP and .NET Technologies. Saqib owns and write contents on mycplus.com since 2004.
Related Post