Jump to content
  • Advertisement
Sign in to follow this  
Prune

Copy/conversion-constructing from a derived class

This topic is 3335 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

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
Advertisement
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
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!