Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing classes from another source in C++, issues initializing the constructor

I have a class called Player that has a constructor that takes 5 float parameters declared in my "player.h" file and then initialized in my "player.cpp" file as shown at the bottom of the post.

Whenever I try to run the program, I get the error:

build/Debug/MinGW-Windows/player.o: In function `Player':
C:\Users\User\Dropbox\NetBeans Workspace\Testing/player.cpp:11: multiple definition of `Player::Player(float, float, float, float, float)'
build/Debug/MinGW-Windows/main.o:C:\Users\User\Dropbox\NetBeans Workspace\Testing/player.h:20: first defined here

What am I doing wrong here? I tried getting rid of the "public:" before the constructor, but that didn't help at all. It says I have multiple definitions of the constructor, but I only initialize it once. I am sure it is something obvious.

The complete source of the two files:

"player.cpp"

#include "player.h"

Player::Player(float x, float y, float z, float rx, float ry) {

}

"player.h"

#ifndef PLAYER_H
#define PLAYER_H

class Player {

public:

    Player(float x, float y, float z, float rx, float ry);
};

#endif
like image 622
CoderTheTyler Avatar asked Jan 23 '26 15:01

CoderTheTyler


1 Answers

You probably haven't protected your .h file.

You include your player.h in main.cpp, there it gets one definition for this compilation unit. And then it's included in player.cpp, where it gets a second definition.

If your compiler doesn't support #pragma once, you'll have to manually protect them with the classical :

#ifndef PLAYER_H
#define PLAYER_H

// all your class definition code here

#endif
like image 156
Stephane Rolland Avatar answered Jan 26 '26 07:01

Stephane Rolland



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!