Noah Siegel
Noah Siegel

Reputation: 5

How to initialize a class with a primitive in C++(like std::string initialized from const char*)

What I've been wondering for a while, across many different languages, now in c++, is how do you initialize an object with a primitive? I'm curious about how std::string initializes with a const char* and I want to know if there's a simple way of doing that. Apologies if this question is badly formatted, I've just not found any like this on stackoverflow and this is my first or second question ever. Thanks!

Upvotes: 0

Views: 41

Answers (1)

thibsc
thibsc

Reputation: 4079

If you can write something like that:

std::string s = "hello world!";

It's because the constructor of the string class takes a const char *

std::string is a std::basic_string<char>

For example, if you want to instantiate an object of your custom class with a primitive data type, you have just to define a constructor that allow it:

class MyCustomClass
{
public:
    MyCustomClass(int a) : m_integer(a) {}
    MyCustomClass(const char* s) : m_integer(std::atoi(s)) {}
    int getValue() const { return m_integer; }

private:
    int m_integer;
};

This class allow you to use it like this:

MyCustomClass mcc1 = 2;    // Use MyCustomClass(int a)
MyCustomClass mcc2 = "12"; // Use MyCustomClass(const char* s)

// Will print : 2
std::cout << mcc1.getValue() << std::endl;
// Will print : 12
std::cout << mcc2.getValue() << std::endl;

Upvotes: 2

Related Questions