0

I have some code I need to convert from Python to C++. Since I do not know C++ well, I would like to use this example to help me understand how a Python class relates/can be converted to a C++ class.

Given the following Python code:

class MyClass(object):
    # Constructor
    def __init__(self, arg1, arg2=True):
        self.Arg1 = arg1
        self.Arg2 = arg2

    # Function __my_func__
    def __my_func__(self, arg3):
        return arg3

What would a proper translation to C++ be?

I've been trying to teach myself how to do this with the tutorial on cplusplus.com, but I still don't understand how I can relate this to Python.

I've also seen some SO questions asking how to convert a Python program to C++ (e.g. Convert Python program to C/C++ code?), but most answers suggest using a specific tool like Cython to do the converting (my desire is to do it by hand).

Community
  • 1
  • 1
Kimbluey
  • 1,199
  • 2
  • 12
  • 23
  • Possible duplicate of [Convert Python program to C/C++ code?](https://stackoverflow.com/q/4650243/608639) – jww Nov 21 '19 at 13:32

1 Answers1

2

It would look something like this. The arg1 and arg2 variables are private, meaning that they're not accessible outside of the class unless you write a getter/setter function (which I've added for arg1).

class MyClass {
    public:
        MyClass (int arg1, bool arg2 = true);
        int myFunc (int arg3);
        int getArg1 ();
        void setArg1 (int arg1);
    private:
        int arg1;  // Can be accessed via the setter/getter
        bool arg2; // Cannot be accessed outside of the class
};

MyClass::MyClass(int arg1, bool arg2 = true) {
    this.arg1 = arg1;
    this.arg2 = arg2;
}

int MyClass::myFunc (int arg3) {
    return arg3;
}

// Getter
int MyClass::getArg1 () {
    return this.arg1;
}

// Setter
void MyClass::setArg1 (int arg1) {
    this.arg1 = arg1;
}
Kimbluey
  • 1,199
  • 2
  • 12
  • 23
Dehli
  • 5,950
  • 5
  • 29
  • 44
  • Do you have any suggestions as to how I would make this question any better without voiding your answer? I didn't think it was too broad, but I guess veterans like to be choosy. I thought SO supported learning for beginners, but I suppose not. – Kimbluey Mar 25 '15 at 18:00
  • It's probably best just to leave it as it is. If you want to ask a more specific question I'd recommend just creating a new one. Sorry it got closed! @Kimbluey – Dehli Mar 25 '15 at 20:58
  • Eh that's okay, I got what I wanted. I just didn't understand why it wasn't acceptable. It's not like I have time to read an entire book (but I definitely bought one anyway **:D**). Plus I went to ask another question and it was like `WARNING, your questions suck!` But anyway thanks again :) – Kimbluey Mar 25 '15 at 21:01
  • 1
    You're welcome. Good luck learning C++! – Dehli Mar 25 '15 at 21:03