从基类构造函数调用纯虚函数

时间:2011-12-25 15:10:54

标签: c++ constructor abstract-class object-lifetime pure-virtual

我有一个包含纯虚函数的基类MyBase:

void PrintStartMessage() = 0

我希望每个派生类在它们的构造函数中调用它

然后我把它放在基类(MyBase)构造函数

 class MyBase
 {
 public:

      virtual void PrintStartMessage() =0;
      MyBase()
      {
           PrintStartMessage();
      }

 };

 class Derived:public MyBase
 {     

 public:
      void  PrintStartMessage(){

      }
 };

void main()
 {
      Derived derived;
 }

但是我收到了链接器错误。

 this is error message : 

 1>------ Build started: Project: s1, Configuration: Debug Win32 ------
 1>Compiling...
 1>s1.cpp
 1>Linking...
 1>s1.obj : error LNK2019: unresolved external symbol "public: virtual void __thiscall MyBase::PrintStartMessage(void)" (?PrintStartMessage@MyBase@@UAEXXZ) referenced in function "public: __thiscall MyBase::MyBase(void)" (??0MyBase@@QAE@XZ)
 1>C:\Users\Shmuelian\Documents\Visual Studio 2008\Projects\s1\Debug\s1.exe : fatal error LNK1120: 1 unresolved externals
 1>s1 - 2 error(s), 0 warning(s)

我想强制所有派生类到......

A- implement it

B- call it in their constructor 

我该怎么做?

8 个答案:

答案 0 :(得分:30)

有很多文章解释了为什么你永远不应该在C ++中的构造函数和析构函数中调用虚函数。请查看herehere,了解在此类通话过程中幕后发生的情况。

简而言之,对象是从基础到派生的构造的。因此,当您尝试从基类构造函数调用虚函数时,尚未发生从派生类重写,因为尚未调用派生构造函数。

答案 1 :(得分:14)

在构造该对象时,尝试从派生中调用纯抽象方法是不安全的。这就像试图将汽油加入汽车,但那辆汽车仍在装配线上,而且油箱尚未放入。

你可以做的最接近的事情就是首先完全构造你的对象然后在之后调用方法:

template <typename T>
T construct_and_print()
{
  T obj;
  obj.PrintStartMessage();

  return obj;
}

int main()
{
    Derived derived = construct_and_print<Derived>();
}

答案 2 :(得分:8)

您无法以您想象的方式执行此操作,因为您无法从基类构造函数中调用派生的虚函数 - 该对象尚未属于派生类型。但你不需要这样做。

在MyBase构造之后调用PrintStartMessage

我们假设你想做这样的事情:

class MyBase {
public:
    virtual void PrintStartMessage() = 0;
    MyBase() {
        printf("Doing MyBase initialization...\n");
        PrintStartMessage(); // ⚠ UB: pure virtual function call ⚠
    }
};

class Derived : public MyBase {
public:
    virtual void PrintStartMessage() { printf("Starting Derived!\n"); }
};

即,所需的输出是:

Doing MyBase initialization...
Starting Derived!

但这正是构造函数的用途!只需废弃虚函数并使Derived的构造函数完成工作:

class MyBase {
public:
    MyBase() { printf("Doing MyBase initialization...\n"); }
};

class Derived : public MyBase {
public:
    Derived() { printf("Starting Derived!\n"); }
};

输出就是我们所期望的:

Doing MyBase initialization...
Starting Derived!

但这并不强制派生类显式实现PrintStartMessage功能。但另一方面,请三思而后行是否有必要,因为无论如何它们总是可以提供一个空的实现。

在MyBase构造之前调用PrintStartMessage

如上所述,如果您想在构建PrintStartMessage之前致电Derived,则无法完成此操作,因为Derived还没有PrintStartMessage个对象被要求。要求PrintStartMessage成为非静态成员是没有意义的,因为它无法访问任何Derived数据成员。

具有工厂功能的静态功能

或者我们可以将其设为静态成员,如下所示:

class MyBase {
public:
    MyBase() {
        printf("Doing MyBase initialization...\n");
    }
};

class Derived : public MyBase {
public:
    static void PrintStartMessage() { printf("Derived specific message.\n"); }
};

一个自然的问题是如何被称为?

我可以看到两种解决方案:一种类似于@greatwolf,你必须手动调用它。但是现在,因为它是一个静态成员,你可以在构造MyBase的实例之前调用它:

template<class T>
T print_and_construct() {
    T::PrintStartMessage();
    return T();
}

int main() {
    Derived derived = print_and_construct<Derived>();
}

输出

Derived specific message.
Doing MyBase initialization...

这种方法会强制所有派生类实现PrintStartMessage。不幸的是,只有当我们使用我们的工厂功能构建它们时才会这样......这是该解决方案的一个巨大缺点。

第二种解决方案是采用奇怪的重复模板模式(CRTP)。通过在编译时告诉MyBase完整的对象类型,它可以在构造函数中执行调用:

template<class T>
class MyBase {
public:
    MyBase() {
        T::PrintStartMessage();
        printf("Doing MyBase initialization...\n");
    }
};

class Derived : public MyBase<Derived> {
public:
    static void PrintStartMessage() { printf("Derived specific message.\n"); }
};

输出符合预期,无需使用专用工厂功能。

使用CRTP

从PrintStartMessage中访问MyBase

正在执行MyBase时,已经可以访问其成员了。我们可以让PrintStartMessage能够访问已调用它的MyBase

template<class T>
class MyBase {
public:
    MyBase() {
        T::PrintStartMessage(this);
        printf("Doing MyBase initialization...\n");
    }
};

class Derived : public MyBase<Derived> {
public:
    static void PrintStartMessage(MyBase<Derived> *p) {
        // We can access p here
        printf("Derived specific message.\n");
    }
};

以下内容也有效且经常使用,虽然有点危险:

template<class T>
class MyBase {
public:
    MyBase() {
        static_cast<T*>(this)->PrintStartMessage();
        printf("Doing MyBase initialization...\n");
    }
};

class Derived : public MyBase<Derived> {
public:
    void PrintStartMessage() {
        // We can access *this member functions here, but only those from MyBase
        // or those of Derived who follow this same restriction. I.e. no
        // Derived data members access as they have not yet been constructed.
        printf("Derived specific message.\n");
    }
};

没有模板解决方案 - 重新设计

另一个选择是稍微重新设计你的代码。 IMO这个实际上是首选解决方案,如果您必须从PrintStartMessage构造中调用被覆盖的MyBase

此提案旨在将DerivedMyBase分开,如下所示:

class ICanPrintStartMessage {
public:
    virtual ~ICanPrintStartMessage() {}
    virtual void PrintStartMessage() = 0;
};

class MyBase {
public:
    MyBase(ICanPrintStartMessage *p) : _p(p) {
        _p->PrintStartMessage();
        printf("Doing MyBase initialization...\n");
    }

    ICanPrintStartMessage *_p;
};

class Derived : public ICanPrintStartMessage {
public:
    virtual void PrintStartMessage() { printf("Starting Derived!!!\n"); }
};

您按如下方式初始化MyBase

int main() {
    Derived d;
    MyBase b(&d);
}

答案 3 :(得分:5)

您不应该在构造函数中调用virtual函数。 Period。您必须找到一些解决方法,例如将PrintStartMessage设为非virtual并将调用显式放在每个构造函数中。

答案 4 :(得分:1)

如果PrintStartMessage()不是纯虚函数而是普通虚函数,编译器就不会抱怨它。但是,您仍然需要弄清楚为什么没有调用PrintStartMessage()的派生版本。

由于派生类在其自己的构造函数之前调用基类的构造函数,因此派生类的行为类似于基类,因此调用基类的函数。

答案 5 :(得分:0)

我知道这是一个古老的问题,但是在编写程序时遇到了相同的问题。

如果您的目标是通过让基类处理共享的初始化代码来减少代码重复,同时又要求派生类在纯虚拟方法中指定它们唯一的代码,那么我决定这样做。

#include <iostream>

class MyBase
{
public:
    virtual void UniqueCode() = 0;
    MyBase() {};
    void init(MyBase & other)
    {
      std::cout << "Shared Code before the unique code" << std::endl;
      other.UniqueCode();
      std::cout << "Shared Code after the unique code" << std::endl << std::endl;
    }
};

class FirstDerived : public MyBase
{
public:
    FirstDerived() : MyBase() { init(*this); };
    void  UniqueCode()
    {
      std::cout << "Code Unique to First Derived Class" << std::endl;
    }
private:
    using MyBase::init;
};

class SecondDerived : public MyBase
{
public:
    SecondDerived() : MyBase() { init(*this); };
    void  UniqueCode()
    {
      std::cout << "Code Unique to Second Derived Class" << std::endl;
    }
private:
    using MyBase::init;
};

int main()
{
    FirstDerived first;
    SecondDerived second;
}

输出为:

 Shared Code before the unique code
 Code Unique to First Derived Class
 Shared Code after the unique code

 Shared Code before the unique code
 Code Unique to Second Derived Class
 Shared Code after the unique code

答案 6 :(得分:0)

面对同样的问题,我想出了一个(并非完美的)解决方案。这样做的目的是向基类提供一个证书,在构造之后将调用纯虚拟init函数。

class A
{
  private:
    static const int checkValue;
  public:
    A(int certificate);
    A(const A& a);
    virtual ~A();
    virtual void init() = 0;
  public:
    template <typename T> static T create();
    template <typeneme T> static T* create_p();
    template <typename T, typename U1> static T create(const U1& u1);
    template <typename T, typename U1> static T* create_p(const U1& u1);
    //... all the required possibilities can be generated by prepro loops
};

const int A::checkValue = 159736482; // or any random value

A::A(int certificate)
{
  assert(certificate == A::checkValue);
}

A::A(const A& a)
{}

A::~A()
{}

template <typename T>
T A::create()
{
  T t(A::checkValue);
  t.init();
  return t;
}

template <typename T>
T* A::create_p()
{
  T* t = new T(A::checkValue);
  t->init();
  return t;
}

template <typename T, typename U1>
T A::create(const U1& u1)
{
  T t(A::checkValue, u1);
  t.init();
  return t;
}

template <typename T, typename U1>
T* A::create_p(const U1& u1)
{
  T* t = new T(A::checkValue, u1);
  t->init();
  return t;
}

class B : public A
{
  public:
    B(int certificate);
    B(const B& b);
    virtual ~B();
    virtual void init();
};

B::B(int certificate) :
  A(certificate)
{}

B::B(const B& b) :
  A(b)
{}

B::~B()
{}

void B::init()
{
  std::cout << "call B::init()" << std::endl;
}

class C : public A
{
  public:
    C(int certificate, double x);
    C(const C& c);
    virtual ~C();
    virtual void init();
  private:
    double x_;
};

C::C(int certificate, double x) :
  A(certificate)
  x_(x)
{}

C::C(const C& c) :
  A(c)
  x_(c.x_)
{}

C::~C()
{}

void C::init()
{
  std::cout << "call C::init()" << std::endl;
}

然后,该类的用户不能在不提供证书的情况下构造实例,但是该证书只能由创建函数生成:

B b = create<B>(); // B::init is called
C c = create<C,double>(3.1415926535); // C::init is called

此外,如果不在构造函数中实现证书传输,则用户无法创建从A B或C继承的新类。然后,基类A具有在构造后将调用init的保证。

答案 7 :(得分:-1)

我可以使用MACROS而不是模板为您的抽象基类提供解决方法/“同伴”,或者完全不使用该语言的“自然”约束。

使用init函数创建基类,例如:

class BaseClass
{
public:
    BaseClass(){}
    virtual ~BaseClass(){}
    virtual void virtualInit( const int i=0 )=0;
};

然后,为构造函数添加一个宏。请注意,没有理由不在此处添加多个构造函数定义,也不必选择多个宏。

#define BASECLASS_INT_CONSTRUCTOR( clazz ) \
    clazz( const int i ) \
    { \
        virtualInit( i ); \
    } 

最后,将宏添加到派生中:

class DervivedClass : public BaseClass
{
public:
    DervivedClass();
    BASECLASS_INT_CONSTRUCTOR( DervivedClass )
    virtual ~DervivedClass();

    void virtualInit( const int i=0 )
    {
        x_=i;
    }

    int x_;
};