Sign in to follow this  
Prune

Copy/conversion-constructing from a derived class

Recommended Posts

What are the rules for copy/conversion (not sure of the right term in this case) a base object from a derived one? Does the compiler automatically generate a copy constructor and cast, or generate a conversion one? For example:
class Bar
{
public:
	Bar(Bar const &o) : _m(o._m) {}
	void Print(void) : { cout << _m << endl; }
protected:
	Bar(int const i) : _m(i) {}
	int _m;
};

class Foo : public Bar
{
public:
	Foo(void) : Bar(5) {}
};

Foo one;
Bar two(one);
two.Print();

The output is 5. If I make the copy constructor of Bar private, the code doesn't compile, so it seems the compiler is using it to do the construction. However, why is it then that if I make it explicit, it's still doing it? I thought that explicit disallows conversions of constructor arguments! Is this a compiler issue, or is there a language rule excepting inheritance-related classes from explicit?

Share this post


Link to post
Share on other sites
explicit means that the constructor can't be used for automatic type conversions for a single argument constructor from the argument type to the class type. In this case it doesn't matter if you make it explicit or not; there's always an implicit conversion from a derived type to a reference of the base type.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this