Reputation: 14281
Is it possible to declare that a member is a subclass of the base classes member?
E.g.
class A {
int a;
}
class B : A {
int b;
}
class Foo {
A *baz;
}
class Bar : Foo {
B *baz; //How can I not shadow baz, but 'redeclare' it as a B?
}
Basically, Bar will always have baz be a B and I want 2 things: a way of showing/enforcing this and also avoiding to have to cast baz everytime its used in Bar. My intuition is that this is not possible, but I dont purport to be a C++ expert.
Upvotes: 3
Views: 1055
Reputation: 120079
You cannot. You can only redeclare a return type of a virtual function.
class Foo {
virtual A *baz();
};
class Bar : public Foo {
B *baz();
};
Upvotes: 4
Reputation: 14724
It depends how baz
is initialized in Foo
. This is a possible solution:
class Foo {
protected:
A *baz;
public:
Foo() : baz(new A) {}
Foo(A *baz_) : baz(baz_) {}
// dtor, copy ctor, copy assign operator required but skipped for brevity
}
class Bar : Foo {
public:
Bar() : Foo(new B) {}
private:
// use this to access baz as a B*
B *baz() { return static_cast<B*>(Foo::baz); }
}
A smart pointer would be preferred over a raw pointer here.
Upvotes: 2
Reputation: 27577
You can't 'redeclare' any name in C++, but here you're not. Within Bar
, baz
is the default with:
baz
or
Bar::baz
and you get to Foo
's with:
Foo::baz
ypu see they have their own scope and therefore unique name.
Upvotes: 0