Subclass and use base class initialiser
I have this:
class foo {
public:
int a;
int b;
int c;
};
Which is fine, but I want to add some operator overloading without modifying class foo:
class bar: public foo {
operator==(const bar &x) const {
开发者_Python百科 return a == x.a;
}
}
Fine so far, but now I need to initialise bar with an array of objects I get from another class. No problem, I can just copy all of the foo variables over to bar in a dedicated constructor:
bar::bar(foo &x) {
a = foo.a;
/* etc */
}
But this seems messy, and if class foo over gets updated, then I have to update bar too. Much preferable if bar could automatically initialise itself (it'll never contain its own data members)
isn't it as simple as making sure Foo has a copy constructor.......
bar::bar(foo &x)
: foo(x)
{
}
class foo {
foo::foo(foo &x)
{
a = foo.a; /* etc */
}
};
Well, easy:
bar::bar(const foo& x)
: foo(x)
{
}
Just use foo
's copy constructor. Everything between the :
and the {
is called the initializer list. You can directly initialize your members and base classes in there. For foo
, the copy constructor could look like the following:
foo::foo(const foo& other)
: a(other.a)
, b(other.b)
, c(other.c)
{
}
Note that I take both arguments by const reference, which is a good practice since you aren't touching the other objects. Also note that writing a copy constructor for foo
yourself is not necessary most of the time, only when your class contains raw pointers (int*
for example). The compiler will generate a copy ctor itself if you don't define one and just make a shallow copy of all data members.
Inheriting constructors can't be done in C++03, but can be approximated. Add these constructors:
template<class T1> bar(const T1& x1) : foo(x1) {}
template<class T1, class T2> bar(const T1& x1, const T2& x2) : foo(x1, x2) {}
template<class T1, class T2, class T3> bar(const T1& x1, const T2& x2, const T3& x3) : foo(x1, x2, x3) {}
// as much as you need...
In C++0x use a single variadic templated constructor and perfect forwarding.
精彩评论