User Defined Conversions

Example of Overloading Typecast Operator

Can you provide an example of overloading a typecast operator for a custom class?

Abstract art representing computer programming

Sure! Let's consider a Vector class where we want to provide a typecast operator to convert a Vector to a std::string for easy printing.

#include <iostream>
#include <string>
#include <sstream>

class Vector {
public:
  float x, y, z;

  Vector(float x, float y, float z)
    : x(x), y(y), z(z) {}

  // Overload the std::string typecast operator
  operator std::string() const {
    std::ostringstream oss;
    oss << "Vector(" << x << ", "
      << y << ", " << z << ")";
    return oss.str();
  }
};

int main() {
  Vector v(1.0f, 2.0f, 3.0f);

  std::string s = v; 
  std::cout << s;
}
Vector(1, 2, 3)

In this example, the Vector class has three float members: x, y, and z. The constructor initializes these members. The operator std::string() function is defined to convert a Vector to a std::string. It uses an std::ostringstream to format the string.

When we assign v to s, the operator std::string() function is called, converting the Vector to a std::string. This allows us to easily print the vector.

Typecast operators can be used to provide convenient and meaningful conversions for your custom types, making your code more readable and expressive.

Answers to questions are automatically generated and may not have been reviewed.

A computer programmer
Part of the course:

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Free, unlimited access

This course includes:

  • 124 Lessons
  • 550+ Code Samples
  • 96% Positive Reviews
  • Regularly Updated
  • Help and FAQ
Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved