jeudi 3 septembre 2015

C++: Can a parent class constructor call the child class's method override? [duplicate]

This question already has an answer here:

I have a child class, and both the child and parent have non-default constructors. The constructor calls a virtual method that the child has overridden. But when I construct the child, the parent's method is called. Why? How can I make this Do What I Mean?

Here's a hypothetical example showing the behavior I'm seeing. It's not my actual code, but it's the same idea:

#include <iostream>
#include <string>

using std::cout;
using std::endl;
using std::string;

class Parent {
 public:
  explicit Parent(int x) {
    cout << classname() << " " << x << endl;
  }
  virtual string classname() {
    return "Parent";
  }
};

class Child : public Parent {
 public:
  explicit Child(int x) : Parent(x) {}
  string classname() override {
    return "Child";
  }
};

int main() {
  // Why does the following print "Parent 4"?
  // And how can I make it print "Child 4" instead?
  Child child(4);
  return 0;
}

Do I have to duplicate the Parent constructor in Child? In my real code this is a pretty non-trivial constructor and duplicating it would make maintenance harder.

Aucun commentaire:

Enregistrer un commentaire