2
Constructor that defines the implicit conversion from string type to type
of your class

Can someone explain in plain terms what implicit conversion from string type to type of your class means?

  • 3
    It probably means a [converting constructor](https://stackoverflow.com/questions/15077466/what-is-a-converting-constructor-in-c-what-is-it-for). – WhozCraig Apr 06 '22 at 08:23

1 Answers1

3

A conversion constructor is basically a constructor that take a single argument of one type (different from the class), and uses it to initialize the object.

Lets say you have the following class:

struct Foo
{
    Foo() = default;  // Defaulted default constructor

    // Conversion constructor, allows construction from int values
    Foo(int)
    {
    }
};

Then you can create Foo object with an int value:

Foo f = 1;  // Equivalent to Foo f = Foo(1)

It also allows assignments from int values:

f = 2;  // Equivalent to f = Foo(2)
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
  • Does it have to be struct or can I use it with just regular classes too? –  Apr 06 '22 at 08:41
  • @00n00r `struct` and `class` are almost exactly the same. The main difference is the default visibility of members, for `class` it's `private` while for `struct` it's `public`. – Some programmer dude Apr 06 '22 at 09:19
  • @Someprogrammerdude just to be pedantic, access and visibility are not interchangeable. Visibility affects name lookup and what goes into an overload set. Access is a check that happens after overload resolution completes. Private data and members are visible, but not accessible to outside code, while code that isn't visible isn't even considered. – Chris Uzdavinis Apr 06 '22 at 15:00
  • The primary difference between struct and class is the default access of struct is public (for members and base classes), while for classes it's private. – Chris Uzdavinis Apr 06 '22 at 15:00