Search code examples
c++inheritancepolymorphismheader-files

expected class-name before '{' token - with header files and cpp files


Like many people asking this question, I am very new to C++ and I can't wrap my head around this error:

Dollar.h:4:31: error: expected class-name before '{' token
    class Dollar: public Currency {

These are my files

main.cpp

#include <iostream>
#include "Dollar.h"

using namespace std;

int main() {
    Dollar * d = new Dollar();
    d->printStatement();
    return 0;
}

Currency.cpp

#include <iostream>
#include "Currency.h"

using namespace std;

class Currency {
    public:
        virtual void printStatement() {
            cout << "I am parent";
        }
};

Currency.h

#ifndef CURRENCY_H
#define CURRENCY_H

class Currency {
    public:
        virtual void printStatement();
};

#endif

Dollar.cpp

#include <iostream>
using namespace std;

void printStatement() {
    cout << "I am dollar";
}

Dollar.h

#ifndef DOLLAR_H
#ifndef DOLLAR_H

class Dollar : public Currency {
    public:
        void printStatement();
};

#endif

Thank you so much for your time and any help is much appreciated.


Solution

  • The error says that the name of a class was expected between : public and { here:

    class Dollar : public Currency {
                          ^^^^^^^^
    

    Currency is not a name of a class, because you haven't defined such class. Yes, you have defined such class in files Currency.cpp and Currency.h, but not in the file Dollar.h where that error occurs.

    Solution: The class Currency has to be defined first before it can be used as a base class. Like so:

    // class is defined first
    class Currency {
        public:
            virtual void printStatement();
    };
    
    // now Currency is a class and it can be used as a base
    class Dollar : public Currency {
        public:
            void printStatement();
    };
    

    Since a class must be defined in all source files where it is used, and the definition must be identical across all source files, it is often useful to define the class in a separate "header" file, such as you have done. In such case you can simply include that header in stead of writing the definition repeatedly in each source file:

    #include "Currency.h"
    

    Currency.cpp contains two definitions for the class Currency. Once in the header that is included, and then second time after that. You may not have multiple definitions for the same class in a single source file.

    Solution: Remove the class definition from Currency.cpp. Instead only define the member function:

    void Currency::printStatement() {
        //...
    }
    

    Finally, you haven't defined Dollar::printStatement. You've defined printStatement, which is not the same thing.