Home > Back-end >  What is the reason encountering "already has a body" error and how to fix it? in my C pr
What is the reason encountering "already has a body" error and how to fix it? in my C pr

Time:12-14

I'm working on a project that consists of sharing objects between multiple classes.

User::User(string username) {  // constructor of User class
    this->name = &username; 
    num_comments = new unsigned int(0);
}

this is my implementation of constructor in cpp file and the definition of class in header file is

class User {  

private:
    string *name; 
    vector<Post> posts; 
    unsigned int *num_comments; 

public:
    
    User(string username)   {}
    ~User() {}
     Post& createPost(string content); 
     
    vector<Post*> getPosts(); 
    int getnumcomments();
    string getName(); 
};

When I try to run my code, I entounter with error C2084: function 'User::User(std::string)' already has a body

I encounter the same error with my other constructors and destructors. So, my mistake is general. What is the reason?

CodePudding user response:

The error message tells it explicitly: you define User::User twice. Once outside and once inside the class declaration.

CodePudding user response:

In your header file, you are defining the constructor with an empty body:

User(string username)   {}

And then in your cpp file, you are defining the same constructor with a non-empty body:

User::User(string username) {  // constructor of User class
    this->name = &username; 
    num_comments = new unsigned int(0);
}

Hence the error. To solve this, in the header file, you need to replace the braces with a semicolon instead:

User(string username);
  • Related