I’m confused about the content in the swift doc:
Notice that the initializer for the EquilateralTriangle class has three different steps:
- Setting the value of properties that the subclass declares.
- Calling the superclass’s initializer.
- Changing the value of properties defined by the superclass. Any additional setup work that uses methods, getters, or setters can also be done at this point.
And then I try the example below in Swift and C++:
Swift
class Base {
init() {
print("Enter Base");
setUp();
print("Leave Base");
}
func setUp() -> Void {
print("base setUp()")
}
}
class Derived: Base {
let number: Int;
override init () {
number = 5;
}
override func setUp() -> Void {
print("derived setUp() (number)")
}
}
let d = Derived()
let b = Base()
Enter Base
derived setUp() 5
Leave Base
Enter Base
base setUp()
Leave Base
C++
#include <iostream>
#include <string>
class Base {
public:
Base() {
std::cout << "Enter Base" << std::endl;
setUp();
std::cout << "Leave Base" << std::endl;
}
virtual void setUp() {
std::cout << "base setUp()" << std::endl;
}
};
class Derived: public Base {
int number;
public:
Derived () {
number = 5;
}
void setUp() override {
std::cout << "derived setUp() " << number << std::endl;
}
};
int main()
{
Derived d = Derived();
Base b = Derived();
}
Enter Base
base setUp()
Leave Base
Enter Base
base setUp()
Leave Base
Based on the two outputs above, it is evident that there are differences between C++ and Swift in terms of their inheritance philosophy. Could someone explain why the behavior differs between the two languages (Why does Swift allow a superclass to access subclass methods)?
I’ve already know the vtable in C++ and its mechanism, but I know nothing about Swift, so it would be nice if you could compare the difference of the underlying implementation between two languages.
Chen Sam is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.