There is the following code:
#include <iostream> class Base { public: char val = 'a'; virtual char GetVal() { return val; } } class Derived : public Base { public: char val = 'A'; virtual char GetVal() { return val; } } int main() { Base *pb = Derived; std::cout << pb->val << std::endl; //Выведет: a std::cout << pb->GetVal() << std::endl; //Выведет: A delete pb; return 0; } From this code, you can see that the member with the identifier val of the base class Base is replaced with another member with the same identifier val in the derived class Derived .
In client code, when using a Base * type pointer that points to an object of type Derived , we can get access to the public val member of the derived class Derived only when using the virtual function GetVal () , which returns the value of this member.
- Is there any other way to access a member with the name val of a derived class that replaces the name of a base class member using a pointer to the base type without resorting to virtual get- replace functions ?
This is interesting because if the base class code is replaced with the following:
class Derived : public Base { public: int val = 65; // был тип char - стал int virtual int GetVal() { // теперь возвращаем объект типа int return val; } } Then an error occurs at the compilation stage " conflicting return type specified for virtual int Derived :: GetVal () ' ", because when overriding a virtual function of a base class, the type it returns must be the same in a derived class.
- How can I get access to a member of a derived class whose name overlaps the name of a member of the base class, but has a different type, while operating with the pointers of the base class?