class Base1{
public:
Base1(){};
virtual ~Base1() = 0;
}
class Derived1 : public Base1{
public:
Derived1(int a) : a(a){};
~Derived1();
int a;
}
class Base2{
public:
Base2(){};
virtual ~Base2() = 0;
}
class Derived2 : public Base2{
public:
Derived2(int b) : b(b){};
~Derived2();
int b;
void func(const Base1 &base1); // How to access Derived1::a here?
}
Given the above class definition, how can I access Derived1::a
in void func(const Base1 &base1)
? I am still new to polymorphism. I tried to use different static_cast or dynamic_cast methods but none of them works. What should I do inside the function so I can access a derived class member from a base class reference?
FYI I can't change the class definition for my coursework requirement, and that is what given to me. I understand that it is simpler to just pass Derived1 as parameter but I am not allow to do so.
CodePudding user response:
Given the above class definition, how can I access
Derived1::a
invoid func(const Base1 &base1)
? ... FYI I can't change the class definition for my coursework requirement, and that is what given to me.
Ideally, you should expose a virtual
method in Base1
that returns an int
(or int&
), and then have Derived1
override that method to return its a
member.
But, given that you are not allowed to change the class definitions, that is not an option.
You need a pointer or reference to a Derived1
object in order to access its a
member directly. Which really leaves you with only 1 choice - you can use dynamic_cast
to typecast the base class reference to the derived class type, eg:
void Derived2::func(const Base1 &base1)
{
// this will raise an exception if the cast fails at runtime
const Derived1 &d = dynamic_cast<const Derived1&>(base1);
// use d.a as needed...
}
Alternatively:
void Derived2::func(const Base1 &base1)
{
// this will return null if the cast fails at runtime
const Derived1 *d = dynamic_cast<const Derived1*>(&base1);
if (d) {
// use d->a as needed...
} else {
// do something else...
}
}