Not constructors and destructors call virtual functions

1. not in the constructor call virtual functions

E.g

class Base{

public:

Base();

virtual void func1() const=0;

}

Base :: Base ()

{

//...

func1 ();

}

class Derived:public Base

{

public:

virtual void func1() const;

}

Derived d is performed when the first call is the base class constructor Base calling func1 is not appropriate in the Base constructor because func1 is a pure virtual function in the base class is not defined, then subclass Derived object has not yet been established. When that is the base class constructor is executed, part of a derived class of the object is being initialized state;

 

If you want to call subclass interface in the constructor, by transmitting the information to the subclasses of the parent class constructor to, for example:

class Base

{

public:

Base(String str);

void func1(String str);

}

Base(String str)

{

//....

func1 (str);

}

class Derived:public Base

{

public:

Derived (str)

:Base(str)

{//.....}

}

 

2. The virtual function call in destructor is meaningless

And the order of the sequence of derived object constructor destruction compared to just the opposite, because when the base class constructor is executed, the derived class virtual function call of the constructor for the base class, the derived class time portion has been destroyed. I.e., when the members of the base class, the object is in an unfinished state.

 

To sum up : If a constructor or destructor call a virtual function, then we should perform the function version of a constructor or destructor belongs corresponding to the type of virtual.

 

 

 

Guess you like

Origin www.cnblogs.com/jiayouya-susu/p/11973567.html