Why should I re-declare a virtual function from an inherited class?

I am working on a simple C ++ program and it is difficult for me to understand the compiler error I received. The problem was caused by the fact that I was trying to create a derived class from a base class. I posted my code below with the same structure, but changed the names.

Baseclass.h

#ifndef BASECLASS_H
#define BASECLASS_H

class BaseClass {

    public:
        BaseClass(void);

        virtual int method1(void) = 0;
        virtual int method2(void) = 0;
        virtual float method3(void) = 0;

};

#endif // BASECLASS_H

DerivedClass.h

#ifndef DERIVEDCLASS_H
#define DERIVEDCLASS_H

#include "DerivedClass.h"

class DerivedClass: public BaseClass
{

    public:
        DerivedClass(void);     
};

#endif // DERIVEDCLASS_H

DerivedClass.cpp

#include "DerivedClass.h"

DerivedClass::DerivedClass(void)
{
}

int DerivedClass::method1(void)
{
  // TODO
} 

int DerivedClass::method2(void)
{
  // TODO
}

float DerivedClass::method3(void) 
{
  // TODO
}

When I try to compile this, I get the following error for all virtual methods:

no 'int DerivedClass::methodX()' member function declared in class 'DerivedClass'

As soon as I declare these methods in "DerivedClass.h", the errors go away as the compiler now knows about the methods.

. DerivedClass.h? #include DerivedClass.h, BaseClass.h, , DerivedClass.cpp . - ?

+4
4

. , , .

. , .. BaseSubtype, method1(), , , , method2() method3()

+6

, :

, , :

; ,

, :

, , . , ( ).

0

, .

  • - .

method1 method2 method3, DerivedClass!! . .

Derivedclass.h :

#ifndef DERIVEDCLASS_H
#define DERIVEDCLASS_H

#include "BaseClass.h"

class DerivedClass: public BaseClass
{

    public:
        DerivedClass(void); 

        virtual int method1(void); // not pure function
        virtual int method2(void);
        virtual float method3(void);
};

#endif // DERIVEDCLASS_H
0

, , , ++ .

( Java), . ++. , , , - .

. ++ - , , .

, . : , - , . , - .

. : ++ 9, , , , .

-1
source

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


All Articles