JohnLXiang
JohnLXiang

Reputation: 178

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

Upvotes: 0

Views: 41

Answers (1)

John Zwinck
John Zwinck

Reputation: 249143

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.

Upvotes: 2

Related Questions