Answer the question
In order to leave comments, you need to log in
Casting a derived class object to a base class?
Experimenting with OOP.
If you bring the derived class object to the base one, the fields declared in the derived class disappear? What if you use link casting?
For example:
class Base{};
class Exp: public Base
{
int i=0;
public:
int Get() const { return i; }
void Set(const int &num) { i=num; }
};
std::vector<Base> MyStack;
Base &GetRef()
{ return *MyStack.begin(); }
int main(){
Exp a;
a.Set(4);
MyStack.push_back(a);
int res=((Exp&)GetRef()).Get(); // Не работает, мусор из стека
}
Answer the question
In order to leave comments, you need to log in
fields declared in a derived class disappear?
Base&
) there will be no such problems, but the reference itself is not a variable (unlike a pointer) - it is just an additional NAME for some other variable or memory area. Therefore, you won't be able to store the reference in the vector - your code won't compile. In a vector, you will need to store pointers. For example, std::vector<Base*>
. Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question