Easy Weekend Refactoring Java to C++
Refactoring from Java to C++
After several hard weeks of RL and coding, I am taking it easy this weekend. I started a little project to increase my fluency in C++ and how to integrate it with make. I am taking some of my adventure game classes and refactoring to C++.
Here is the Thing class as it looks in Java.
Thing.java
import java.io.Serializable;
public class Thing implements Serializable{
private String name;
private String description;
private boolean takable;
private boolean movable;
public Thing(String name, String description, boolean takable, boolean movable){
this.name = name;
this.description = description;
this.takable = takable;
this.movable = movable;
}
public String getName(){
return this.name;
}
public String getDescription(){
return this.description;
}
public boolean getTakable( ){
return this.takable;
}
public boolean getMovable( ){
return this. movable;
}
public String describe(){
return " Here is a " + this.getName() + ": It is" + this.getDescription();
}
}
Pretty straightforward. It is one of my base classes. And, here is the final look in C++. Doing it the alleged “correct” way is why there are two files, a header file and an implementation file. Using this method, I can mirror how I do it in Java with one class per file.
thing.h and thing.cpp
class Thing{
protected:
std::string name;
std::string description;
bool takable;
bool movable;
public:
Thing(std::string name, std::string description, bool takable, bool movable);
std::string getName();
std::string getDescription();
bool getTakable( );
bool getMovable( );
std::string describe();
};
Thing::Thing(std::string name, std::string description, bool takable, bool movable){
this->name = name;
this->description = description;
this->takable = takable;
this->movable = movable;
}
std::string Thing::getName(){
return this->name;
}
std::string Thing::getDescription(){
return this->description;
}
bool Thing::getTakable( ){
return this->takable;
}
bool Thing::getMovable( ){
return this->movable;
}
std::string Thing::describe(){
return " Here is a " + this->getName() + ": It is" + this->getDescription();
}
In this form, I use the header file for the class format, but I only declare all the functions. I don’t implement the functions. In the thing.cpp file, I implement individual class functions. I just have to prepend the class name to each function, as in Thing::getTakable( ).
I’m not going to go through explaining everything here. Most of it is pretty easy to see and if not, there are hosts of videos for learning both Java and C++.
Anyway, can’t stay long. Happy coding!