Understanding Inheritance in C ++

I am trying to learn C ++ and wrote this code. According to my oversight, this code should produce output like "Derived Class", but output "Base Class". Please help me figure this out.

#include <iostream> 
using namespace std; 

class Base { 
    public: 
    char* name; 
    void display() { 
         cout << name << endl; 
    } 

};

class Derived: public Base { 
   public: 
   char* name; 
   void display() { 
       cout << name << ", " << Base::name << endl; 
   } 
}; 

int main() { 
   Derived d; 
   d.name = "Derived Class"; 
   d.Base::name = "Base Class"; 

   Derived* dptr = &d; 

   Base* bptr = dptr; 

   bptr->display();
}

Please consider me a newbie and explain why its conclusion "Base Class"

+4
source share
5 answers

You need to make a method display() virtual

Like this:

class Base{ 
    public: 
    char* name; 
    virtual void display() { 
         cout << name << endl; 
 } 

virtual allows derived classes to "redefine" the functions of the base class.

+2
source

http://www.parashift.com/c++-faq/dyn-binding.html

Non-virtual member functions are statically resolved. This member function is selected statically (at compile time) based on the type of pointer (or reference) to the object.

, - ( ). - ( ) , / .

0

, , . virtual , .

0

++ . "", bptr- > .

0

( , ) , . , , , , display() name, " ".

0

Source: https://habr.com/ru/post/1534977/


All Articles