Basic C ++ Inheritance

At school and in hundreds of online video, C ++ inheritance is taught through a single file; all classes are declared above the core. I searched everywhere to find one example of how inheritance works in conjunction with header files, but I am surprised that no one has ever asked about this before.

How does C ++ inheritance work in conjunction with header files? Does each subclass need its own new header file that extends the base header, or can the subclass definition file define functions for the superclass header file?

Also, does an abstract class affect the above questions?

+4
source share
4 answers

In C ++, the contents of the header files are inserted by the preprocessor, where they are #included. Therefore, there is no significant difference between putting all the definitions that you use in one file and separating these definitions between different header files. The same rules apply - in particular, you need to declare the parent class in front of the child class, so you will need the #includecorresponding parent class in front of the child class. Abstract classes do not change any of these discussions. Header files are what the preprocessor gives us people, not what the C ++ language as such understands.

+5
source

- , , .

. ".cpp" #include . , . - :

#include "foo.h"

... foo.h, . , , , , , , .

, , . (), , , . :

class Sub: public Base // the compiler must be able to see the 
                       // definition of 'Base' at this point.

, . - :

class Base {...};
class Sub: public Base {...};

... , ( ). , , , :

// Base.h
#ifndef BASE_H
#define BASE_H

class Base {...};

#endif

// Sub.h
#ifndef SUB_H
#define SUB_H

#include "Base.h"

class Base: public Sub {...};

#endif

, Base , Sub . , : . , , , , , / , .

+3

,

. . . , , .

, , , , , , .

?

- ( .cpp), , . , .

, ?

.

+1

, , .

So, I do not need to include a title for each derived class. Since the question asks how inheritance works in conjunction with the header file, here is a simple demo

File1: base.h

   class Shape
   {
      public:
         void setWidth(int w)
         {
            width = w;
         }
         void setHeight(int h)
         {
            height = h;
         }
      protected:
         int width;
         int height;
};

File2: derived .h

#include "base.h"
// Derived class
class Rectangle: public Shape
{
   public:
       int getArea()
       { 
          return (width * height); 
       }
};

File 3: main.cpp

#include"derived.h"
using namespace std;
int main(void)
{
    Rectangle Rect;
    Rect.setWidth(5);
    Rect.setHeight(7);

    // Print the area of the object.
    cout << "Total area: " << Rect.getArea() << endl;
    return 0;
}

The output will be 35. I hope this helps.

0
source

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


All Articles