派生类对象构造后调用虚函数

时间:2016-01-28 22:02:57

标签: c++ constructor polymorphism

以下是一些示例代码:

#include <iostream>

class A {
public:
    virtual void foo() {
        std::cout << "base" << std::endl;
    }

    A() {
        foo();
    }
};

class B : public A {
    int a;
public:
    void foo() {
        std::cout << "derived" << std::endl;
    }

    B(int a) :
        a(a) {}
};

int main() {
    B o(1);
    return 0;
}

每次构造一些foo()派生对象时,我都希望调用A。我不想在每个派生类构造函数中显式调用foo()

有没有办法以优雅的方式做到这一点?

2 个答案:

答案 0 :(得分:3)

无论你做什么,都无法从基类构造函数中调用重写的subprocess.PIPE。调用基类构造函数时,派生类对象尚未构造,因此您无法调用其任何方法或访问其任何成员。对于虚函数和常规函数也是如此。在基类构造函数中,foo()指针指向基类,而不是派生类。

答案 1 :(得分:1)

一个潜在的解决方法是将构造委托给客户必须调用的单独函数。然后在构造之后让该函数调用foo:

class A {
public:
    virtual void foo() {
        std::cout << "base" << std::endl;
    }

    template<typename T, typename ... Args>
    static T construct(Args ... args)
    {
        T newT{ args... };
        newT.foo();
        return std::move(newT);
    }

protected:
    A() {
        //Construct A
    }
};
class B : public A {
    int a;
public:
    void foo() {
        std::cout << "derived" << std::endl;
    }

    B(int a) :
        a(a) {}
};

int main()
{
    B o = A::construct<B>(1);
    A a = A::construct<A>();
    return 0;
}
相关问题