Skip to content

Commit 6831130

Browse files
committed
[interop][SwiftToCxx] docs: add a user guide section on class inheritance
1 parent 7eefb30 commit 6831130

File tree

1 file changed

+41
-1
lines changed

1 file changed

+41
-1
lines changed

docs/CppInteroperability/UserGuide-CallingSwiftFromC++.md

Lines changed: 41 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ A Swift library author might want to expose their interface to C++, to allow a C
77
**NOTE:** This document does not go over the following Swift language features yet:
88

99
* Closures
10-
* inheritance
10+
* overriden methods/properties in classes
1111
* Existential types (any P)
1212
* Nested types
1313
* Operators
@@ -626,6 +626,46 @@ The Swift `Person` class instance that C++ variable `p` referenced gets dealloca
626626
at the end of `createAndUsePerson` as the two C++ values that referenced it
627627
inside of `createAndUsePerson` were destroyed.
628628
629+
### Class inheritance
630+
631+
A Swift class that inherits from another class is bridged to C++ with that inheritance
632+
relationship preserved in the C++ class hierarchy generated for these Swift classes. For example, given the following two Swift classes:
633+
634+
```swift
635+
// Swift module 'Transport'
636+
public class Vehicle {
637+
}
638+
public final class Bicycle: Vehicle {
639+
}
640+
```
641+
642+
Get a corresponding C++ class hierachy in C++:
643+
644+
```c++
645+
class Vehicle { ... };
646+
class Bicycle final : public Vehicle {};
647+
```
648+
649+
This allows C++ code to implicitly cast derived class instances to base class reference values, like in the example below:
650+
651+
```c++
652+
#include "Transport-Swift.h"
653+
654+
using namespace Transport;
655+
656+
void doSomethingWithVehicle(Transport::Vehicle vehicle) {
657+
...
658+
}
659+
660+
void useBicycle() {
661+
auto bike = Bicycle::init();
662+
doSomethingWithVehicle(bike);
663+
}
664+
```
665+
666+
Swift classes that are marked as `final` are also marked `final` in C++.
667+
Swift classes that are not marked as `final` should not be derived from in C++.
668+
629669
## Accessing Properties In C++
630670

631671
Swift allows structures and classes to define stored and computed properties. Stored properties store constant and variable values as part of an instance, whereas computed properties calculate (rather than store) a value. The stored and the computed properties from Swift types are bridged over as getter `get...` and setter `set...` methods in C++. Setter methods are not marked as `const` and should only be invoked on non `const` instances of the bridged types.

0 commit comments

Comments
 (0)