Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ expected opening brace as well as redefinition error

So I'm trying to define my class in the .h file and write the constructor in the cpp file, like so:

.h file:

class Player : protected Character{
    public:
        Player(sf::Vector2f starting_pos, std::list<Object *> *around) : Character(around);

.cpp file:

Player::Player(sf::Vector2f starting_pos, std::list<Object *> *around){
    //code
}

Now the compiler gives both of these errors:

character.h:25:90: error: expected ‘{’ at end of input
   25 |         Player(sf::Vector2f starting_pos, std::list<Object *> *around) : Character(around);

and

character.cpp:3:1: error: redefinition of ‘Player::Player(sf::Vector2f, std::__cxx11::list<Object*>*)’
    3 | Player::Player(sf::Vector2f starting_pos, std::list<Object *> *around){
      | ^~~~~~

So it seems to me that it wants me to define the code in the .h file AND THEN complains that I didn't do so in the .cpp file. If I put the code directly in the .h file it works, but I don't want to do this.

I'm not sure if these have anything to do with it so here is some more info:

character is an abstract class that inherits from object, and player inherits from character. Also: there is a second error in the cpp file that says that object is not accessible within this context.

I've found a ton of people with a missing closing brace, but nothing about missing opening braces.

Thanks for any help

like image 920
Yapoz Avatar asked Nov 29 '25 20:11

Yapoz


2 Answers

In your header file you have

Player(sf::Vector2f starting_pos, std::list<Object *> *around) : Character(around);

Which is causing the error. Since you use an initializer list there, the compiler expects the full function definitions to be there as well. Simply remove the initializer for Character from that line, and move it into your C++ file.

.h file

Player(sf::Vector2f starting_pos, std::list<Object *> *around);

.cpp file

Player::Player(sf::Vector2f starting_pos, std::list<Object *> *around) : Character(around) {
    //code
}
like image 74
ChrisMM Avatar answered Dec 01 '25 10:12

ChrisMM


Your ctor-initialiser goes on the definition, not the declaration, of the constructor.

You confused the compiler, by [effectively] writing a definition (it must be a definition as it has the ctor-initialiser on it) without a {} (because you meant for it to be a declaration) … and then later providing [another] definition.

like image 34
Lightness Races in Orbit Avatar answered Dec 01 '25 08:12

Lightness Races in Orbit