0

I'm still learning the beauty of C++. I came across some code today and hopefully someone can give me some guidance. I have 2 classes

class B
{
public:
    B( std::string s )
        : m_string( s )
    {
    }

private:
    std::string m_string;
};

class A
{
public:
    A( B b )
        : m_b( b )
    {
    }

private:
    B m_b;
};

Main.cpp

A a = A(std::string("hello"));

I'm a bit confused about how can such initialization work? How does the compiler know that the std::string("hello) is to be passed to B's constructor instead?

I was trying to find relevant documentation but no luck..

1 Answer 1

2

When a class has a constructor taking a single argument, that constructor can be used to implicitly convert that argument to an instance of that class. This means that wherever a B is required, your B( std::string s ) constructor allows passing a string instead.

If you want to inhibit this implicit conversion, you write explicit B( std::string s ). Some people consider this good practice for most single-argument constructors.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.