Virtual constructors

Is there a need for virtual constructors? If so, can anyone post the script?

+3
source share
9 answers

If you are talking about virtual destructors in C ++ (there are no such things as virtual constructors), then they should always be used if you are using your child classes polymorphically.

class A
{
  ~A();
}

class B : public A
{
  ~B();
}

A* pB = new B();
delete pB; // NOTE: WILL NOT CALL B destructor

class A
{
  virtual ~A();
}

class B : public A
{
  virtual ~B();
}

A* pB = new B();
delete pB; // NOTE: WILL CALL B destructor

Edit: Not sure why I have a lower limit for this (it would be helpful if you left a comment ...), but also read here

http://blogs.msdn.com/oldnewthing/archive/2004/05/07/127826.aspx

+8

As always: see the C ++ FAQ lite: virtual functions .

" ", /!

, , ++ ...

+3

Delphi - , .

factory, -, , . -

- ....

type
  MyMetaTypeRef = class of MyBaseClass;

var
  theRef : MyMetaTypeRef;
  inst : MyBaseClass;
begin 
  theRef := GetTheMetaTypeFromAFactory(); 
  inst := theRef.Create(); // Use polymorphic behaviour to create the class
+2

, , . , ( "" ), . . (, , ), abstract factory, , .

+2

? ++, , .

+1

. , .

0

++ , , . , , -, , . .

, , , , . :

Superclass *object = NULL;
if (condition) {
    object = new Subclass1();
}
else {
    object = new Subclass2();
}
object.setMeUp(args);

... . Objective-C, "alloc" , , .

, Abstract Factory, , ++ Java, .

0

++ ( ). , . , , . , , .

, , (. ).

, , . 9 ++, , Scott Meyers ( ). , , .

#include <iostream>
#include <vector>

class Animal {

    public:

        Animal(){
            std::cout << "Animal Constructor Invoked." << std::endl;
        }

        virtual void eat() {
            std::cout << "I eat like a generic animal.\n";
        }

        //always make destructors virtual in base classes
        virtual ~Animal() {

        }

};

class Wolf : public Animal {

    public:

        Wolf(){
            std::cout << "Wolf Constructor Invoked." << std::endl;
        }

        void eat() {
            std::cout << "I eat like a wolf!" << std::endl;
        }

};


int main() {

    Wolf wolf;
    std::cout << "-------------" << std::endl;
    wolf.eat();

}

:

Animal Constructor Invoked.
Wolf Constructor Invoked.
-------------
I eat like a wolf!
-1

++. , ++ . . , . desgin. ++, , .

-1
source

Source: https://habr.com/ru/post/1696940/


All Articles