1

I have the following header:

#include <string>

using namespace std;

enum COLOR {Green, Blue, White, Black, Brown};


class Animal{
    private:
    string _name;
    COLOR _color;

    public:
    Animal();
    ~Animal();
    void speak() const;
    void move() const;
} ;

And the following .cpp implementation:

#include <iostream>
#include <string>
#include "Animal.h"
Animal::Animal(): _name("unknown")
    {
        cout << "constructing Animal object" << endl;
    };
Animal::~Animal()
    {
        cout << "destructing Animal object" << endl;
    }
void Animal::speak()
    {
        cout << "Animal speaks" << endl;
    }
void Animal:: move(){};

However, the speak() and move() functions are giving me an error: "no declaration matches Animal::speak()" . If I remove the 'const' at the tail of the declaration, there are no issues in compilation. How do I correctly implement a const function in a .cpp file?

Ymi
  • 609
  • 6
  • 18
  • Put the const behind `void Animal::move() const{}` in the implementation – infinitezero Nov 20 '21 at 07:59
  • I assumed the question would be closed. But someone else already put the answer. – infinitezero Nov 20 '21 at 08:02
  • You should think about splitting definitions into cpp files in general, especially for small functions. As long you did not compile with LTO, your code typically will be much less optimized if you don't have implementation in header files! – Klaus Nov 20 '21 at 08:55
  • BTW, don't write `using namespace std;`, especially in your **header files**. Doing so pollutes the global namespace and may cause naming conflicts in unrelated places. [Why is "using namespace std;" considered bad practice?](https://stackoverflow.com/q/1452721/1458097) – heap underrun Nov 20 '21 at 10:05
  • @Klaus What do you mean by " splitting definitions into cpp files" ? Do you mean that I should just forgo the header file for small programs like this and do everything in the cpp for optimization? – Ymi Nov 21 '21 at 03:21
  • 1
    No! The opposite! Put everything in the header, especially if the methods are small. – Klaus Nov 21 '21 at 08:39

1 Answers1

3

You forget to put const in the implementation.

Change your code to:

void Animal::speak() const
{
    cout << "Animal speaks" << endl;
}
void Animal::move() const {};