Language Guide: Classes & Objects¶
This section covers how Kotlin classes, interfaces, and objects are transpiled to C++.
Classes¶
Kotlin classes are transpiled to C++ class declarations. Primary constructor parameters with val or var become public fields.
Kotlin:
C++:
class Person {
public:
std::string name;
int32_t age;
Person(std::string name, int32_t age) : name(name), age(age) {}
void greet() {
// println helper from ktox-lib.hpp
println("Hello, " + ktox::toString(name) + "");
}
};
Inheritance & Interfaces¶
ktox-cpp supports single inheritance and multiple interfaces, mapping them to C++ public inheritance.
Kotlin:
interface Drawable {
fun draw()
}
open class Shape(val color: String)
class Circle(color: String, val radius: Double) : Shape(color), Drawable {
override fun draw() {
println("Drawing a $color circle")
}
}
C++:
class Drawable {
public:
virtual ~Drawable() = default;
virtual void draw() = 0;
};
class Shape {
public:
std::string color;
Shape(std::string color) : color(color) {}
virtual ~Shape() = default;
};
class Circle : public Shape, public Drawable {
public:
double radius;
Circle(std::string color, double radius)
: Shape(color), radius(radius) {}
void draw() override {
println("Drawing a " + ktox::toString(color) + " circle");
}
};
Objects and Companion Objects¶
Kotlin object declarations and companion objects are transpiled to C++ classes with static members or as singletons.
Companion Objects¶
Companion objects are transpiled to static members within the containing C++ class. Calls use the scope resolution operator ::.
Kotlin:
class Config(val host: String) {
companion object {
val DEFAULT_PORT = 8080
fun createDefault() = Config("localhost")
}
}
C++:
class Config {
public:
std::string host;
Config(std::string host) : host(host) {}
static constexpr auto DEFAULT_PORT = 8080;
static Config createDefault() {
return Config("localhost");
}
};
// Usage:
const auto cfg = Config::createDefault();
Object Declarations¶
Kotlin object declarations are transpiled to Meyer's singletons in C++.
Kotlin:
C++:
class Database {
public:
static Database& instance() {
static Database inst;
return inst;
}
std::string name = "Production";
void connect() { /* ... */ }
private:
Database() = default;
};
Data Classes¶
data class declarations generate standard C++ boilerplate like operator== and toString().
Kotlin:
C++:
class Point {
public:
int32_t x;
int32_t y;
Point(int32_t x, int32_t y) : x(x), y(y) {}
bool operator==(const Point& other) const {
return x == other.x && y == other.y;
}
std::string toString() const {
return "Point(x=" + ktox::toString(x) + ", y=" + ktox::toString(y) + ")";
}
};
Operator Overloading¶
ktox-cpp maps Kotlin operator functions to C++ operator overloads.
Kotlin:
class Vec2(val x: Float, val y: Float) {
operator fun plus(other: Vec2) = Vec2(x + other.x, y + other.y)
}
C++: