Calling class methods derived from an abstract class [C ++]

You will have to forgive me if this is really a basic question; I haven't used C ++ for a long time, so I forgot how much it works.

Anyway, I have a base class and a couple of derived classes like this (super simplistic, but the essence is the same):

class Base
{
public:
   Base () { }
   int SomeFunction (int x, int y); // abstract definition
};

class Derived1 : public Base
{
public:
   Derived1() : Base() { }
   int SomeFunction (int x, int y)
   {
      // actual implementation
      return 4;
   }
};

class Derived2 : public Base
{
public:
   Derived2() : Base() { }
   int SomeFunction (int x, int y)
   {
      // actual implementation
      return 7;
   }
};

Later in mainI have a list of objects Base:

Base *baseobjects[10];

Later I populate this array with instances of Derived1and Derived2. This works with baseobjects[i] = &newDerived1(where newDerived1is an instance of the class Derived1). This is all wonderful.

, , , baseobjects SomeFunction , , . #, , , -, ++ :

int result = baseobjects[i]->SomeFunction(a, b);

LNK2019 , -, , Base , . , , , , , . ?

+2
4

virtual. , , virtual.

class Base
{
public:
   Base () { }
   virtual int SomeFunction (int x, int y) = 0; // abstract definition
};

, , , virtual. , - .

class Base
{
public:
   //Base () {} // This is not required, the default provided constructor is similar.
   virtual ~Base() {} // virtual destructor.
   virtual int SomeFunction (int x, int y) = 0; // abstract definition
};

:

, :

= 0, Base::SomeFunction() -.

, = 0 , : , , (re) , .

, .

+8

, .

class Base
{
public:
   Base () { }
   virtual int SomeFunction (int x, int y); // abstract definition
}

Seccond - , .

class Derived1 : public Base
{ 
 public:
    Derived1() : Base() { }
    int SomeFunction (int x, int y)
    {
        // actual implementation
        return 4;
    }
}
+2

- SomeFunction()

, Base :

class Base
{
public:
    Base() { }
    virtual int SomeFunction(int x, int y) = 0;
};

virtual .

+1

ereOn, (.. ), . , , ( , , - ).

Note also that if you are after a clean abstract definition, you must add = 0functions to the declaration as follows:

class Base
{
public:
   Base () { }
   virtual int SomeFunction (int x, int y) = 0; // pure abstract definition
};

This allows the compiler to know that classes derived from Basemust provide their own implementation SomeFunction.

0
source

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


All Articles