Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding Inheritance in C++ [duplicate]

I am trying to learn C++, and wrote this code. According to my understaing this code need to produce output as "Derived Class" but output is "Base Class". Please help me understand this.

#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 as a beginner and explain why its output is "Base Class"

like image 527
someone Avatar asked Apr 04 '14 06:04

someone


People also ask

What is repeated inheritance?

Repeated inheritance occurs whenever (as a result of multiple inheritance) two or more of the ancestors of a class D have a common parent A. D is then called a repeated descendant of A, and A a repeated ancestor of D.

Does C allow multiple inheritance?

In Multiple inheritance, one class can have more than one superclass and inherit features from all its parent classes. As shown in the below diagram, class C inherits the features of class A and B. But C# does not support multiple class inheritance.

Which inheritance may lead to duplicate?

Explanation : Multipath inheritance may lead to duplication of inherited members from a "grandparent" base class.

What is inheritance in C?

Inheritance is a mechanism of reusing and extending existing classes without modifying them, thus producing hierarchical relationships between them. Inheritance is almost like embedding an object into a class.


1 Answers

You need to make the display() method virtual

Like this:

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

virtual allows derived classes to 'override' the base class' functions.

like image 165
AndyG Avatar answered Nov 09 '22 19:11

AndyG