简体   繁体   中英

C++ implicitly calling class member's constructor when initializing the class instance

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..

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM