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"
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.
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.
Explanation : Multipath inheritance may lead to duplication of inherited members from a "grandparent" base class.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With