Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problem with separating a class into header (.h) and source (.cpp) file

So I tried separating a class into declarantion and defenition and I thought i was doing well but when I tried to compile it I get this error message. I don't see what the problem is but I suspect it has something to do with a simple syntax rule.

Error messages

...         ...: g++ -o main.exe Dog.cpp main.cpp
Dog.cpp:11:6: error: no declaration matches 'void Dog::setName(int)'
 void Dog::setName(int name){
      ^~~
In file included from Dog.cpp:1:
Dog.h:10:8: note: candidate is: 'void Dog::setName(std::__cxx11::string)'
   void setName(string name);
        ^~~~~~~
Dog.h:6:7: note: 'class Dog' defined here
 class Dog{
       ^~~
Dog.cpp:23:5: error: no declaration matches 'int Dog::getAge()'
 int Dog::getAge(){
     ^~~
In file included from Dog.cpp:1:
Dog.h:11:10: note: candidate is: 'std::__cxx11::string Dog::getAge()'
   string getAge();
          ^~~~~~
Dog.h:6:7: note: 'class Dog' defined here
 class Dog{
       ^~~

These are the used files: main.cpp

#include <iostream>
#include <string>
#include "Dog.h"
using namespace std;


//Functions



int main(){
  //Variables
  string userInput;

  //Code
  Dog dolly("Dolly", 3);

  cout<<dolly.getName();
  cout<<dolly.getAge();


  return 0;
}

Dog.h

#ifndef DOG_H
#define DOG_H
#include <string>
using namespace std;

class Dog{
public:
  Dog(string name, int age);
  string getName();
  void setName(string name);
  string getAge();
  void setAge(int age);
private:
  int Age;
  string Name;
protected:

};


#endif // DOG_H

Dog.cpp

#include "Dog.h"
#include <iostream>
#include <string>
using namespace std;

Dog::Dog(string name, int age){
  setName(name);
  setAge(age);
};

void Dog::setName(int name){
  Name = name;
};

string Dog::getName(){
  return Name;
};

void Dog::setAge(int age){
  Age = age;
};

int Dog::getAge(){
  return Age;
};

Thanks in advance for your answers!

like image 586
samu_242 Avatar asked Jun 04 '26 09:06

samu_242


1 Answers

The error message is quite clear.

Your function signatures don't match.

In your header you declare

void setName(string name);

But in your implementation file you have

void Dog::setName(int name)

Same issue with getAge. The signatures don't match.

like image 150
Jesper Juhl Avatar answered Jun 05 '26 23:06

Jesper Juhl