Python to C++, A Data Scientist’s Journey to Learning a New Language — Classes

Daniel Benson
Geek Culture
Published in
7 min readJul 3, 2021

Introduction

Welcome back, brave readers, to another installment of the Python to C++ Series. In our last meeting we went over the importance and use of the function in Python and C++. Today we will be expanding upon this idea by delving into the world of classes. We will go over some basic use-cases of classes then create our own examples by putting together a class in each language that can be used to develop an RPG character.

Classes

In the previous installment I mentioned that a function can be used to group together lines of code that we may wish to repeat frequently throughout our program. A class is a grouping of functions that work together to complete a common goal. For instance, in the case of our example today we will be making a class that creates a character based on a number of different factors: we will have a function for our character’s name, a function for our character’s race, for their speciality, etc.

In Python a class is created by first defining our class followed by the name we want the class to be; naming conventions follow capitalization of each word with no space between words:

class ClassName():

Every class we create must start with an initializing function. This function initializes values to any important data when the new object or class is called and created. This function will include any variables that we wish to carry through the entire class. It is defined as any other function we create but must have the name __init__ to allow the computer to recognize this is the initializing function. Within the parentheses the self attribute must be included, this allows the recognition of class variables and data throughout the entire class. Within the body of the __init__ function we include the class variables that we want carried throughout; these variables must be instantiated using the self. method as shown below:

def __init__(self, att2, att3, att4):
self.att2 = att2
self.att3 = att3
self.att4 = att4

The rest of the class is made up of whatever functions are needed to be included; again self must be passed as an attribute for each function to allow the recognition of the class’s properties. Within these functions the class variables, or object properties, can be called by again using the self. method:

def func2(self):
print(self.att2)
return self.att3 + self.att4

Values within the class properties can also be changed by calling the property using the self. method and setting it equal to the new value of interest:

def func3(self):
if self.att2 > self.att3:
self.att4 = self.att2
else:
self.att4 = self.att3

In C++ a class, or object, is created in similar fashion by defining the object as a class followed by giving the class a name; the body of the class must then be enclosed in curly braces:

class ClassName
{
<class body>
};

The “initializing function” in a C++ class is indicated by setting the class to public, private, or protected. These are access specifiers that tell the computer whether the attributes and methods (class functions) can be accessed outside of the class or not. Public allows access outside of the class; private does not allow access outside of the class; protected only allows access outside of the class in instances of inheritance, which we will discuss a bit later. We can indicate multiple access specifiers if there are some parts of the class we wish to remain private and the rest public. The body of this access specifier will include the attributes and methods of the class which are set up like any other variable or function; notice though that unlike in python when setting class attributes within a method we must still return the attribute whereas in python we do not need to specify this return:

public:    std::string att1;
std::string att2;
int att3;
double att4;
bool att5;
std::string setAtt1()
{
std::cout << “What is att1?”;
std::cin >> att1;
return att1;
};
std::string setAtt2()
{
std::cout << “What is att2?”;
std::cin >> att2;
return att2;
};
int att3PlusAtt4()
{
att3 = 5;
att4 = 10.6;
return att3 + att4;
};
bool setAtt5()
{
if (att3PlusAtt4() > 5)
{
att5 = true;
}
else
{
att5 = false;
}
};
private:
std::string att6 = “CLASSIFIED”;
int att7 = 42;

Calling and Using a Class

In Python a class can be called by simply instantiating a new variable to the object call:

myClass = ClassName(“hello readers”, 1, 2)

To access the attributes and methods within this new object we use the dot method:

var = myClass.func2()
myClass.func3()
var2 = myClass.att4
print(var2) # will print out a boolean value

In C++ a class is called in a fairly similar way. First the call to the class is made followed by the name of our new object.

int main()
{
ClassName newClass;
}

Just like in Python C++ class attributes and methods are called using the dot method:

newClass.setAtt1();
newClass.setAtt2();
newClass.setAtt4();
newClass.setAtt5();
std::cout << newClass.att1 << std::endl;
std::cout << newClass.att2 << std::endl;
std::cout << newClass.att4 << std::endl;
std::cout << newClass.att5 << std::endl;

Class Inheritance

There may be instances in which we wish to create multiple classes but each of these classes share a number of attributes. In this case we can create a class that inherits these attributes from some parent class. For instance we can create a parent class:

class Parent():
def __init__(self, att1, att2):
self.att1 = att1
self.att2 = att2
def print_att_1(self):
print(att1)
def print_att_2(self):
print(att2)

Then we can use the attributes from the parent class in a new child class by creating the new class and using the parent class as an attribute; the init function will include all attributes carried over from the parent class as well as any new attributes we wish to include in the child class. Finally, within the body of the init class we must include the super() method which allows us to copy over the attributes from the parent class:

class Child(Parent):
def __init__(self, att1, att2, att3, att4):
super().__init__(att1, att2)
self.att3 = att3
self.att4 = att4
def print_att_3(self):
print(att3)
def print_att_4(self):
print(att4)

In C++ we can create a parent class like so:

class Parent
{
public:
int att1;
}

When we create the child class we specify the inheritance from the parent class by defining the child class and name, using a colon as a separator, then specifying the parent’s access mode and the name of the parent class; this gives the child class access to everything within the body of the parent’s public or private access-mode. From here we then just create the class body as we normally would, including the child’s access mode and whatever attributes and methods we want to include:

class Child : public Parent
{
public:
int att2;
}

Calling and accessing the attributes and methods of a child class is the same as if we were calling any other class.

Character Class Example

The following is a class coded in Python that creates an RPG character including a name, race, speciality, hit points, and magic points.

Python:

class Character():
""" A class that holds character information """
def __init__(self, name="", race="", specialty="", hp=0, mp=0):
self.name = name
self.race = race
self.specialty = specialty
self.hp = hp
self.mp = mp
def set_name(self):
""" Sets character name """
print("What is your name?")
self.name = input()
def set_race(self):
""" Sets character race """
print("What is your race? Choose between human, elf, or
dwarf.")
self.race = input()
def set_specialty(self):
""" Sets character class/specialty """
print("What is your specialty (or class)? Choose between
warrior, mage, or rogue.")
self.specialty = input()
def set_hp(self):
if self.specialty == "Warrior":
self.hp = 25
elif self.specialty == "Mage":
self.hp = 15
elif self.specialty == "Rogue":
self.hp = 20
print(f"You have {self.hp} hit points.")
def set_mp(self):
if self.specialty == "Warrior":
self.mp = 5
elif self.specialty == "Mage":
self.mp = 15
elif self.specialty == "Rogue":
self.mp = 10
print(f"You have {self.mp} magic points.")
def view_character_stats(self):
print(f"Name: {self.name}")
print(f"Race: {self.race}")
print(f"Class: {self.specialty}")
print(f"HP: {self.hp}")
print(f"MP: {self.mp}")
newChar = Character()
newChar.set_name()
newChar.set_race()
newChar.set_specialty()
newChar.set_hp()
newChar.set_mp()
newChar.view_character_stats()

returns:

$ python3 classes.py>> What is your name?
>> Daniel
>> What is your race? Choose between human, elf, or dwarf.
>> Human
>> What is your specialty (or class)? Choose between warrior, mage,
or rogue.
>> Warrior
>> You have 25 hit points.
>> You have 5 magic points.
>> Name: Daniel
>> Race: Human
>> Class: Warrior
>> HP: 25
>> MP: 5

C++:

#include <iostream>
#include <string>
class Character
{
public:
std::string name;
std::string race;
std::string specialty;
int hp;
int mp;
std::string setName()
{
std::cout << "What is your name?\n";
std::cin >> name;
return name;
};
std::string setRace()
{
std::cout << "What is your race? Choose between human,
elf, or dwarf.\n";
std::cin >> race;
return race;
};
std::string setSpecialty()
{
std::cout << "What is your specialty (or class)? Choose
between warrior, mage, or rogue.\n";
std::cin >> specialty;
return specialty;
};
int setHP()
{
if (specialty == "Warrior")
{
hp = 25;
}
else if (specialty == "Mage")
{
hp = 15;
}
else if (specialty == "Rogue")
{
hp = 20;
}
std::cout << "Your hp is " << hp << std::endl;
return hp;
};
int setMP()
{
if (specialty == "Warrior")
{
mp = 5;
}
else if (specialty == "Mage")
{
mp = 15;
}
else if (specialty == "Rogue")
{
mp = 10;
}
std::cout << "Your mp is " << mp << std::endl;
return mp;
};
void viewCharStats()
{
std::cout << "Name: " << name << std::endl;
std::cout << "Race: " << race << std::endl;
std::cout << "Class: " << specialty << std::endl;
std::cout << "HP: " << hp << std::endl;
std::cout << "MP: " << mp << std::endl;
};
};int main()
{
Character myChar; // Create new character object
myChar.setName(); // Call setName method
myChar.setRace(); // Call setRace method
myChar.setSpecialty(); // Call setSpeciality method
myChar.setHP(); // Call setHP method
myChar.setMP(); // Call setMP method
std::cout << myChar.name << std::endl;
myChar.viewCharStats(); // Call viewCharStats method
return 0;
};

returns:

$ g++ -o classes classes.cpp
$ ./classes
>> What is your name?
>> Daniel
>> What is your race? Choose between human, elf, or dwarf.
>> Elf
>> What is your specialty (or class)? Choose between warrior, mage,
or rogue.
>> Mage
>> Your hp is 15
>> Your mp is 15
>> Daniel
>> Name: Daniel
>> Race: Elf
>> Class: Mage
>> HP: 15
>> MP: 15

Thank you, brave readers, for joining me again on another journey into the Python to C++ Series. I hope to see you next time and as always keep on reppin’ on and happy coding!

--

--

Daniel Benson
Geek Culture

I am a Data Scientist and writer prone to excitement and passion. I look forward to a future I am able to focus those characteristics into work I love.