blog
blog copied to clipboard
C++ Class with Pointer and Reference Example: GameTeam
GameTeam/Player.h
#ifndef GAMETEAM_PLAYER_H
#define GAMETEAM_PLAYER_H
#include <string>
using namespace std;
class Player {
private:
string name;
int score;
public:
void setName(string);
void setScore(int);
string getName() const;
int getScore() const;
};
#endif //GAMETEAM_PLAYER_H
GameTeam/Player.cpp
#include <string>
#include "Player.h"
using namespace std;
void Player::setName(string new_name) {
name = new_name;
}
void Player::setScore(int new_score) {
score = new_score;
}
string Player::getName() const {
return name;
}
int Player::getScore() const {
return score;
}
GameTeam/main.cpp
#include <iostream>
#include <string>
#include "Player.h"
using namespace std;
// Function prototypes
void printPlayerInfo(const Player&);
void changePlayer(Player&, string, int);
Player createPlayer(string, int);
Player* createPlayerWithPointer(string, int);
int main() {
Player player1, player2;
Player* player_ptr = nullptr;
player1.setName("Alice");
player1.setScore(50);
printPlayerInfo(player1);
changePlayer(player1, "Bob", 100);
printPlayerInfo(player1);
player2 = createPlayer("Jake", 200);
printPlayerInfo(player2);
player_ptr = createPlayerWithPointer("Jenny", 300);
printPlayerInfo(*player_ptr);
// Free dynamically allocated memory.
// Avoid memory leaks (the value of the original memory space is accessed by other objects).
delete player_ptr;
// Make player_ptr a null pointer.
// Avoid dangling pointer (the pointer pointing to an empty memory space).
player_ptr = nullptr;
return 0;
}
void printPlayerInfo(const Player& player) {
cout << player.getName() << endl;
cout << player.getScore() << endl;
}
void changePlayer(Player& p, string new_name, int new_score) {
p.setName(new_name);
p.setScore(new_score);
}
Player createPlayer(string new_name, int new_score) {
Player p;
p.setName(new_name);
p.setScore(new_score);
return p;
}
//Player* createPlayerWithPointer(string new_name, int new_score) {
// Player p;
// Player* p_ptr = &p;
// p.setName(new_name);
// p.setScore(new_score);
// return p_ptr; // The address of the local variable may escape the function.
// // When the function ends, the address of the local variable (p) disappears.
//}
Player* createPlayerWithPointer(string new_name, int new_score) {
Player* p_ptr = new Player;
(*p_ptr).setName(new_name); // p_ptr->setName(new_name);
(*p_ptr).setScore(new_score); // p_ptr->setScore(new_score);
return p_ptr;
}
Output:
Alice
50
Bob
100
Jake
200
Jenny
300