chacham15
chacham15

Reputation: 14281

Can you 'redeclare' a variable in a subclass?

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

Answers (3)

n. m. could be an AI
n. m. could be an AI

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

Oktalist
Oktalist

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

Paul Evans
Paul Evans

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

Related Questions