Search code examples
c++functionclassvirtual

Redefinition of class function error C++


I have my base class Gate, whilst the derived class is AND (XOR etc.). The virtual function I have in my base class is for determining an output, but when I prototype it in AND.h and try and implement it with AND.cpp I get the redefinition error on compile. I am sure I have included everything properly.

Gate header

#ifndef GATE_H
#define GATE_H

class Gate{
    public:
        // various functions etc.

        virtual bool output();   // **PROBLEM FUNCTION**

};

#endif

Gate source

#include "Gate.h"

//*various function declarations but not virtual declaration*

Derived class "AND"

#ifndef AND_H_INCLUDED
#define AND_H_INCLUDED

class AND: public Gate{
public:
    bool output(bool A, bool B){}
};
#endif // AND_H_INCLUDED

and where my IDE puts my error occuring in the AND.h file

#include "AND.h"

bool AND::output(bool A, bool B){
    if (A && B == true){
        Out = true;
    } else {
        Out = false;
    }

    return Out;
}

Out in this case is an inherited variable.


Solution

  • You're providing two definitions of AND::output. One in the header, which is empty, and another in the implementation file, which is not empty. Looks like your header should have:

    bool output(bool A, bool B);
    

    Note that you will not be able to use these output functions polymorphically because they do not have the same arguments as the declaration in Gate.