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?

6
  • Put the const behind void Animal::move() const{} in the implementation Commented Nov 20, 2021 at 7:59
  • I assumed the question would be closed. But someone else already put the answer. Commented Nov 20, 2021 at 8: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! Commented Nov 20, 2021 at 8: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? Commented Nov 20, 2021 at 10:05
  • 1
    No! The opposite! Put everything in the header, especially if the methods are small. Commented Nov 21, 2021 at 8:39

1 Answer 1

5

You forget to put const in the implementation.

Change your code to:

void Animal::speak() const
{
    cout << "Animal speaks" << endl;
}
void Animal::move() const {};
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.