I'm working through a Udemy course on C++ and just came across this. In my lesson on copy constructors, I kind of jumped the gun on what he was teaching, paused the video and started coding what I thought he was abt to talk abt. But I was wrong. He did something different. But my code still worked, still got the desired result. This is a damn good forum, so I know I'll get excellent feedback on this issue.
In my Player class, I have the getters/setters for name, health and xp, the only three variables used.
In my main.cpp, this is what I did:
1 2 3 4 5 6
|
void display_Player(const Player& source){
std::cout << "Name:\t" << source.getName() << std::endl;
std::cout << "Health:\t" << source.getHealth() << std::endl;
std::cout << "XP:\t\t" << source.getXp() << std::endl;
std::cout << "-----------------------------\n";
}
|
In my Player cpp/f files, I didnt create a copy constructor. But this worked anyway.
Now, in my Player cpp/h files, after turning the video back on, I was instructed to do this in my player.h
Player(const Player &source);
and this in my player.cpp
1 2 3 4
|
Player::Player(const Player &source)
: name(source.name), health(source.health), xp(source.xp) {
std::cout << "In copy ctor for " << source.name << std::endl;
}
|
And in my main.cpp, I changed the display_Player function to
1 2 3 4 5 6
|
void display_Player(Player p){
std::cout << "Name:\t" << p.getName() << std::endl;
std::cout << "Health:\t" << p.getHealth() << std::endl;
std::cout << "XP:\t\t" << p.getXp() << std::endl;
std::cout << "-----------------------------\n";
}
|
And it works the same as the one I originally did. So my question is this:
Is the way I did the copy constructor okay? Or is it necessary to create the copy ctor in the header file and implement the function in the class .cpp file?