C++ virtual method not called as expected

拜拜、爱过 提交于 2021-02-11 04:21:17

问题


I'm fiddling around with proper overriding of virtual methods. I chain some constructors and in the base class constructor I call a virtual method.

Call chain should be as followed:

B(p)->A(p)->B.foo(p)

Call chain is in C++:

B(p)->A(p)->A.foo(p)

Call chain is in C#:

B(p)->A(p)->B.foo(p)

So in other words, in C# behaviour is like expected, in C++ it isn't.

C++ Code:

#include <cstdio>

class A {
public:
  A();
  A(int);

  virtual void foo(int s);
};

class B : public A {
public:
  B();
  B(int s) : A(s) {};

  virtual void foo(int s) override;
};

A::A() {
  std::printf("A\r\n");
};

A::A(int s) : A() {
  std::printf("A: %d\r\n", s);
  foo(s);
};

void A::foo(int s) {
  std::printf("A::foo(%d)\r\n", s);
}

B::B() : A(){
  std::printf("B\r\n");
};

void B::foo(int s) {
  std::printf("B::foo(%d)\r\n", s);
}

int main(int argc, char* argv[]) {
  B b(2);
}

Output:

A
A: 2
A::foo(2)

C# Code:

using System;

namespace demo {
class A{
  public A() {
    Console.WriteLine("A");
  }

  public A(int s) : this(){
    Console.WriteLine("A: " + s.ToString());
    foo(s);
  }

  public virtual void foo(int s) {
    Console.WriteLine(string.Format("A:foo({0})", s));
  }
}

class B : A{
  public B() : base() {
    Console.WriteLine("B");
  }

  public B(int s) : base(s) {
  }

  public override void foo(int s) {
    Console.WriteLine(string.Format("B:foo({0})", s));
  }
}

  static class Run {
    static void Main() {
      new B(2);
    }
  }
}

Output:

A
A: 2
B::foo(2)

Why isn't the overriden method of class B called in C++? How do I have to override it correctly?


回答1:


This is just the way C++ works. Virtual functions do not behave virtually during object construction and destruction.



来源:https://stackoverflow.com/questions/41457747/c-virtual-method-not-called-as-expected

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!