Skip to main content
GameDev.net gamedev.net
🔒 Locked

Copy/conversion-constructing from a derived class

Started by Prune Jun 5, 2009 at 2:18 PM 0 replies 700+ views
Original Post
Prune
Prune
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?
"But who prays for Satan? Who, in eighteen centuries, has had the common humanity to pray for the one sinner that needed it most?" --Mark Twain

~~~~~~~~~~~~~~~Looking for a high-performance, easy to use, and lightweight math library? http://www.cmldev.net/ (note: I'm not associated with that project; just a user)
SiCrane
SiCrane
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.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.